【问题标题】:Vue.js recursive component's data including propsVue.js 递归组件的数据,包括 props
【发布时间】:2021-05-22 10:56:34
【问题描述】:

我在 vue.js 中使用递归组件。每个组件都有一个数组,其中一个值作为道具从父组件传递。如何创建数组以正确包含值/道具?

这里是用简化(未经测试)的代码来展示理论问题的细节(我知道这个例子会导致无限递归:-):

我的组件.vue

<template>
  {{my_array}}
  <my-component :my_counter="my_array.counter">
</template>

<script>
module.exports = {
  props: ['my_counter'],
  name: 'my-component', 
  data: function () {
    return {
      new_counter: this.my_counter+1,
      my_array: [name: "static name", counter: this.new_counter]
    }
  },
 }
</script>

虽然 new_counter 作为 my_counter 属性正确传递给子组件,但 my_array.counter 没有正确更新为新值。

当我直接将 new_counter 作为 my_counter 属性传递时(不使用数组)。它有效。

我想我需要使用某种反应性数据。但是,我找不到具有计算属性、方法等的解决方案...如何使 my_array 由传递的道具更新?

您对解决这个问题有什么建议?

【问题讨论】:

    标签: vue.js recursion vue-component vue-props


    【解决方案1】:

    我对 Vue.js 还是很陌生,我在使用它和 Nuxt.js 时也遇到过类似的问题。 虽然,我有一个例子可以帮助你。 你尝试过这样的事情吗?

    <template>
      {{my_array}}
      <my-component :my_counter="compA()">
    </template>
    
    <script>
    module.exports = {
      props: ['my_counter'],
      name: 'my-component', 
      computed: {
        compA() {
           const my_counter = this.my_counter ? this.my_counter : []; 
           let my_array = [name: "static name", counter: my_counter];
           return my_array;
        }
      }
     }
    </script>
    

    【讨论】:

    • 问题依然存在:此时变量 my_counter 为“未定义”。但是,当显示属性时,变量 my:counter 会正确显示。
    【解决方案2】:

    您的代码的问题是 my_array 在使用道具后进行了初始化,但随后没有更新。 你必须像这样添加一个观察者:

    watch: {
      my_counter(value) {
        this.my_array = {
          ...this.my_array,
          counter: value
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-22
      • 2018-04-14
      • 2017-09-15
      • 2017-05-28
      • 1970-01-01
      • 2020-07-01
      • 2016-03-12
      • 2016-10-22
      相关资源
      最近更新 更多