1

I'm having a hard time understanding why I can't display what is returned by data.

From the code below, {{userId}}, {{test}} do not get printed but everything else does. For example the texts User with id, test:, Public profile of user and the content of {{$route.params.used_id}}.

Why is that the case and what do I need to do to fix this?

<template>
  <div>
    <h1>User with id {{userId}}</h1>
    <h1>test: {{test}}</h1>
    <h1>{{user_id}}</h1>
    <p>Public profile of user</p>
    <p>{{$route.params.user_id}}</p>
  </div>
</template>

<script>
export default {
  props: ["user_id"],
  data: function() {
    return {
        //id is name of the dynamic segment we created in router
      userId: this.$route.params.user_id,
      test: "test"
    };
  }
};
</script>

<style lang="scss">
</style>

Errors from console:

[Vue warn]: Property or method "userId" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

[Vue warn]: Property or method "test" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
7
  • Any errors in console ? Commented Jan 29, 2020 at 17:58
  • Yes, I didn't think of looking at that, let me edit my post Commented Jan 29, 2020 at 18:00
  • you should to assign userId in your mounted() function Commented Jan 29, 2020 at 18:04
  • @Nipun Jain, the solution that you posted and removed worked for me. Commented Jan 29, 2020 at 18:05
  • I think you downvoted that .. Commented Jan 29, 2020 at 18:06

2 Answers 2

3

Try changing your data property like this

data () {
    return {
        //id is name of the dynamic segment we created in router
      userId: this.$route.params.user_id,
      test: "test"
    }
  }

As you are using this inside data

Sign up to request clarification or add additional context in comments.

Comments

2

You mustn't use this way:

data: function() {
  return {
    userId: this.$route.params.user_id,
    test: "test"
  };
}

Because is a closure. Closures have access the scope of outer function. Please see this link: https://developer.mozilla.org/docs/Web/JavaScript/Guide/Closures

The correct way is that:

data() {
  return {
    userId: this.$route.params.user_id,
    test: "test"
  };
}

Because is a method and can access this variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.