gpt4 book ai didi

javascript - Vue 和 Vuex : computed property isn't called when changing state

转载 作者:行者123 更新时间:2023-12-02 02:42:43 24 4
gpt4 key购买 nike

我对 Vue 和 Vuex 还很陌生,所以请耐心等待。

我想在更改 state.template 时调用计算函数 versions(),但我没有这样做。更具体地说,当 state.template.versions 更改时。

这是当 state.template.versions 更改时我想要重新渲染的组件的一部分。您还可以看到我想要调用的计算属性 versions():

    <el-dropdown-menu class="el-dropdown-menu--wide"
slot="dropdown">
<div v-for="version in versions"
:key="version.id">
...
</div>
</el-dropdown-menu>
...
computed: {
...mapState('documents', ['template', 'activeVersion']),
...mapGetters('documents', ['documentVersions', 'documentVersionById', 'documentFirstVersion']),
versions () {
return this.documentVersions.map(function (version) {
const v = {
id: version.id,
name: 'Draft Version',
effectiveDate: '',
status: 'Draft version',
}
return v
})
},

这是 setter/getter :

  documentVersions (state) {
return state.template ? state.template.versions : []
},

这是操作:

  createProductionVersion (context, data) {
return new Promise((resolve, reject) => {
documentsService.createProductionVersion(data).then(result => {
context.state.template.versions.push(data) // <-- Here I'm changing state.template. I would expect versions() to be called
context.commit('template', context.state.template)

resolve(result)
})

这是突变:

  template (state, template) {
state.template = template
},

我读到,在某些情况下,Vue 无法检测对数组所做的更改,但 .push() 似乎可以检测到。来源:https://v2.vuejs.org/v2/guide/list.html#Caveats

知道为什么当我更新context.state.template.versions时计算属性没有被调用吗?

最佳答案

问题可能来自于state.template = template。您猜对了,这是一个 react 性问题,但不是来自数组 react 性,而是来自 template 对象。

Vue 无法检测属性添加或删除。这包括影响复杂对象的属性。为此,您需要使用 Vue.set

所以你的突变应该是:

template (state, template) {
Vue.set(state, "template", template)
},

https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

关于javascript - Vue 和 Vuex : computed property isn't called when changing state,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63299620/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com