【问题标题】:Vuejs: listen to props changes and use itVuejs:监听 props 变化并使用它
【发布时间】:2020-03-15 17:03:23
【问题描述】:

我正在使用 Vue JS 开发一个项目,我需要观察 props 的变化并在 <span> 中调用它。

我使用了watch(),它显示props值已分配。

但是当我在 <span> 中调用它时,值没有显示出来。

props: ['verifyText', 'verifyValue', 'profileId', 'logged', 'verifyType', 'status'],
    watch: {
        verifyText: function () { // watch it
            this.verify_text = this.verifyText;
        },
        verifyValue: function () {
            this.verify_value = this.verifyValue;
        },
        verifyType: function () {
            this.verify_type = this.verifyType;
        }
    },
    data() {
        return {
            verify_type: this.verifyType,
            verify_text: this.verifyText,
            verify_value: this.verifyValue,
        }

    },

//using inside span
<span>{{verify_text}}</span>

【问题讨论】:

  • 你在使用 Vuex 吗?
  • 是的。我正在使用 Vuex
  • 乍一看它应该可以工作。您在&lt;span&gt; 中看到了什么价值?问题是它不更新还是根本不渲染任何东西?例如如果您最初将verify_text 内的data 设置为某个虚拟值,您看到渲染了吗?还不清楚为什么您将道具复制到 data 属性,而不是直接使用道具。例如{{ verifyText }}。使用 watch 将 props 复制到 data 通常是潜在设计缺陷的标志。
  • 是的。我将它用作{{ verifyText }},但它不起作用。这就是为什么我试图分配给另一个变量以检查它是否正在分配。当我最初为verify_text 设置一个值时,它会显示在 vue.xml 中。但是当prop值发生变化时,并没有得到新的值。

标签: vuejs2 watch vue-props


【解决方案1】:

接收并插入从“watch”更改的新数据

试试这个。

props: ['verifyText', 'verifyValue', 'profileId', 'logged', 'verifyType', 'status'],
watch: {
   verifyText: function (new_value) {
       this.verify_text = new_value;
   }
},
data() {
   return {
      verify_text: this.verifyText,
   }
},
//using inside span
<span>{{verify_text}}</span>

【讨论】:

    【解决方案2】:

    我通过查看父组件中的 verify_text 解决了这个问题。

    'verify_text': function (value) {
        this.verify_text = value;
      },
    

    verify_type 和 verify_value 相同 谢谢大家的回复。

    【讨论】:

      猜你喜欢
      • 2018-12-19
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      • 2013-07-22
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 2018-07-20
      相关资源
      最近更新 更多