Vue js данные не отображаются в шаблоне - PullRequest
1 голос
/ 29 января 2020

Мне трудно понять, почему я не могу отобразить то, что возвращает data.

Из приведенного ниже кода {{userId}}, {{test}} не печатают, но все остальное делает. Например, тексты User with id, test:, Public profile of user и содержание {{$route.params.used_id}}.

Почему это так и что мне нужно сделать, чтобы это исправить?

<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>

Ошибки с консоли:

[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.

Ответы [ 2 ]

3 голосов
/ 29 января 2020

Попробуйте изменить свойство данных следующим образом

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

Поскольку вы используете this внутри data

2 голосов
/ 29 января 2020

Вы не должны использовать этот способ:

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

Потому что это закрытие. Закрытия имеют доступ к сфере действия внешних функций. Пожалуйста, смотрите эту ссылку: https://developer.mozilla.org/docs/Web/JavaScript/Guide/Closures

Правильный путь таков:

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

Потому что это метод и может получить доступ к переменной this.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...