【问题标题】:DOM is not updating when data variable changes in VueJS当 VueJS 中的数据变量更改时,DOM 不会更新
【发布时间】:2021-09-06 14:51:55
【问题描述】:

我正在尝试更新数组数组并将其呈现为反应变量,但 DOM 并未反映这些更改。

为此,我使用了 2 个组件,一个父组件和一个子组件:

父组件 实例化子组件并传递一个方法(fetchOptionsFn)作为prop,它获取一些数据并更新位于子组件中的数组

<component :is="DynamicDataPairForm"
            :fetchOptionsFn="fetchOptionsFn"

fetchOptionsFn (search, loading, selectOptionsArray, index) {
      if (search.length >= 3) {
        pptDocumentLibraryService.findByTitle(search).then(res => {
          selectOptionsArray[index] = res.data
        }).catch(err => console.log(err))
      }

子组件 定义一个空数组,在 DOM 中定义一个 SELECT,当搜索完成时,这个数组被父继承函数修改。

<tr v-for="(entity,index) in filteredEntityList" :key="entity[entityIdField]">
<v-select
:options="selectEntityArray[index]"
@search="(search, loading) => {
fetchSelectEntityOptions(search, loading, index) }"
/>
</tr>

props: {
 fetchOptionsFn: { type: Function, required: false, default: () => {} },
},
data: {
 selectEntityArray: []
},
methods: {
 fetchSelectEntityOptions (search, loading, index) {
      this.fetchOptionsFn(search, loading, this.selectEntityArray, index)
    }
}

当这个函数被调用(fetchSelectEntityOptions),但数组(selectEntityArray)在DOM中没有改变时,问题就来了。

有什么想法吗? 谢谢!

【问题讨论】:

  • 你使用的Vue是什么版本的?
  • 2.6 版@MichalLevý

标签: javascript vue.js vuejs2


【解决方案1】:

似乎您可能需要在子组件中定义 index 数据属性,否则我不确定 :options="selectEntityArray[index]" 属性中引用的是什么/哪个 index。 然后你还需要在 fetchSelectEntityOptions 函数中设置索引。

所以,也许是这样的:

<v-select
:options="selectEntityArray[index]"
@search="(search, loading) => {
fetchSelectEntityOptions(search, loading, index) }"
/>

props: {
 fetchOptionsFn: { type: Function, required: false, default: () => {} },
},
data: {
 selectEntityArray: [],
 index: null,
},
methods: {
 fetchSelectEntityOptions (search, loading, index) {
      this.index = index;
      this.fetchOptionsFn(search, loading, this.selectEntityArray, index);
    }
}

【讨论】:

  • 抱歉代码不完整,索引实体是从 v-for 循环中获取的。 @InvisibleGorilla
【解决方案2】:

Vue 2 有一些你应该知道的 Change Detection Caveats...

Vue 无法检测到数组的以下更改:

  1. 当您直接使用索引设置项目时,例如vm.items[indexOfItem] = newValue
  2. 当您修改数组的长度时,例如vm.items.length = newLength

所以你需要换行:

selectOptionsArray[index] = res.data

到:

Vue.set(selectOptionsArray, index, res.data)

【讨论】:

    猜你喜欢
    • 2018-10-06
    • 2020-08-26
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 2018-01-13
    • 2022-01-13
    • 2019-05-18
    • 1970-01-01
    相关资源
    最近更新 更多