Vue JS数据未显示在模板上

时间:2020-01-29 17:53:27

标签: vue.js vuejs2

我很难理解为什么我无法显示data返回的内容。

根据下面的代码,{{userId}}{{test}}不会被打印出来,但其他所有内容都会得到打印。例如,文本User with idtest: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 个答案:

答案 0 :(得分:3)

尝试这样更改数据属性

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

this内使用data

答案 1 :(得分:2)

您不得使用这种方式:

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

因为是闭包。闭包可以访问外部函数的范围。请查看此链接:https://github.com/wso2/docs-apim/issues/498

正确的方法是:

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

因为是一种方法,可以访问this变量。