【问题标题】:Props displays in template but not in functions道具显示在模板中,但不显示在函数中
【发布时间】:2019-11-26 16:29:15
【问题描述】:

我的 _id 道具很好地显示在这个子模板中,但是 console.log(this._id) 在 function 中没有显示任何内容,甚至没有“未定义”这是我的子模板:

<template>
  <div>
    LIST
    {{ _id }} // OK , I CAN SEE IT 
  </div>
</template>

<script>
import axios from "axios";
axios.defaults.withCredentials = true;
export default {
  name: "messages",
  props: ["_id"],
  data() {
    return {
      messages: []
    };
  },

  methods: {
    getMessages: function() {
      console.log(this._id);  // NOTHING SHOWN
      axios
        .post(this.server + "getMessages", { _id: this._id })
        .then(response => {
          this.users = response.data;
        })
        .catch(function(error) {
          console.log(error);
        });
    }
  },
  mounted: function() {
    console.log(this._id); // NOTHING SHOWN
    this.getMessages();
  }
};
</script>

请帮助我,我无法理解这种行为。请问怎么可能,console.log(this._id)没有任何工作,那么我怎样才能获得_id prop变量呢?

编辑:这是我在父模板中的组件调用:

 <messages :_id="this.user._id"></messages>

编辑 2: 哦,我想我知道了,这是因为 this.user._id 来自父 axios 调用异步,所以它没有及时出现! 这是有效的,我可以在孩子中使用 console.log(this._id):

<messages :_id="1111111111"></messages>

在调用子组件之前有什么方法可以等待 this.user._id 被填充?

由现象解决

【问题讨论】:

  • 您在将组件添加到模板时是否告知_id 的值?
  • 是的,因为它显示在子模板中。我会把它添加到帖子中谢谢你
  • 你试过括号语法(this['_id'])吗?
  • 谢谢,console.log(this['_id']) 还没有空白...
  • @harmoniuscool 如果需要,您可以使用条件渲染。 &lt;some-component v-if="someCondition"&gt;&lt;/some-component&gt;

标签: vuejs2


【解决方案1】:

主要问题是您访问的属性可以在父组件中动态呈现。

要解决这个问题,请将conditional rendering 用于应该以这种方式获取任何动态道具的任何子组件:

<template>
  <child-component v-if="someData"></child-component>
</template>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 2017-08-07
    • 1970-01-01
    • 2017-11-24
    • 2016-10-15
    相关资源
    最近更新 更多