【问题标题】:Vue js data not displaying on templateVue js数据未显示在模板上
【发布时间】:2020-05-15 07:05:25
【问题描述】:

我很难理解为什么我无法显示 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.

【问题讨论】:

  • 控制台有错误吗?
  • 是的,我没想到看那个,让我编辑我的帖子
  • 你应该在你的mounted()函数中分配userId
  • @Nipun Jain,您发布和删除的解决方案对我有用。
  • 我认为你对此投了反对票..

标签: vue.js vuejs2


【解决方案1】:

你不能这样使用:

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变量。

【讨论】:

    【解决方案2】:

    尝试像这样更改您的数据属性

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

    当您在 data 中使用 this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-26
      • 1970-01-01
      • 2019-12-01
      • 2018-10-27
      • 2020-10-08
      • 2023-03-28
      • 1970-01-01
      • 2020-09-22
      相关资源
      最近更新 更多