【问题标题】:How to Add new Property Object in State Vuex/Vue/Nuxt如何在状态 Vuex/Vue/Nuxt 中添加新的属性对象
【发布时间】:2021-01-07 08:26:57
【问题描述】:

我有一个状态,我想将新属性 foo: 'bar' 放到 detail 状态

export const state = () => ({
  detail: {a: 'b', c: 'd'}
})

export const mutations = {
  SET (state, data) {
    state.detail.foo = 'bar'
  }
}

我在 html 中显示状态

<template>
  <div>{{ data}}</div>
  /* {a: 'b', c: 'd'} */
</template>
<script>
..
  computed: {
    ...mapState({
      data: state => state.detail
    })
  },
..
</script>

数据显示{a: 'b', c: 'd'},但是当我单击按钮添加foo: 'bar' 时,状态会改变,但不会在html 中刷新。我按F5(刷新浏览器)显示新数据foo: 'bar'

【问题讨论】:

  • option1:向状态添加观察者。如果由于您添加了某些内容而导致状态发生更改,它会自动刷新它 选项2:将状态加载到组件内部的计算中 选项3:添加:key 并更新键的值以强制重新渲染michaelnthiessen.com/force-re-render

标签: javascript vue.js vue-component vuex nuxt.js


【解决方案1】:

使用 getter,它们会在更改时重新渲染

export const state = () => ({
  detail: {a: 'b', c: 'd'}
})

export const mutations = {
  SET (state, data) {
    state.detail.foo = 'bar'
  }
}

export const getters = {
   detail: (state) => state.detail 
}

在你的模板中

<template>
  <div>{{ data}}</div>
  /* {a: 'b', c: 'd'} */
</template>
<script>
..
  computed: {
    ...mapGetters({
      data: "detail"
    })
  },
..
</script>

别忘了正确导入

import { mapGetters } from "vuex"

【讨论】:

  • 感谢您的解释!我试过了,但不行。 @Boussadjra Brahim 回答它的工作..
  • 不,没有错误。我以前使用过你的代码,结果和我的问题一样。然后尝试编码 Boussadjra Brahim 并保留你的代码(我使用 getter 来获取数据,而不是像以前那样声明)。
【解决方案2】:

在你的商店代码中导入 vue 然后使用Vue.set(state.detail,"foo" , 'bar')

import Vue from 'vue'
....

export const mutations = {
  SET (state, data) {
   Vue.set(state.detail,"foo" , 'bar')
  }
}

【讨论】:

  • 成功了,谢谢!你知道我的问题吗?我的代码用于更改状态,如果属性不存在,则不显示最新数据。如果有该属性,则显示最新数据。这是在 state 中导入 vue 的最佳实践吗?
  • 是的,这是避免反应性警告的好习惯
猜你喜欢
  • 2017-01-10
  • 1970-01-01
  • 2020-04-07
  • 2020-08-13
  • 2019-04-23
  • 2017-03-26
  • 2018-06-22
  • 2017-07-08
  • 2017-07-28
相关资源
最近更新 更多