【问题标题】:Vuex state change doe not refresh the Vue on WebVuex 状态更改不会刷新 Vue on Web
【发布时间】:2019-09-25 22:45:17
【问题描述】:

我对 Vue 非常陌生,并且在现有代码方面遇到了问题。我已经计算了我的 Vuex 对象的属性

computed: {
...mapGetters([
  'selectedObject'
])
},

在我的 Store.js 中,我将一个新对象添加到我的数组中,但 Vue 没有刷新。请注意,js是插入一个子对象

addNew({ commit, state }, payload) {
  state.currentObject.paintings.push({
    'config': {
      'formName': 'My New Picture',
      'orientation': 'portrait',
      'referenceNumber': '',
      'formType': ''
    },
    'id': (+new Date()),
    'containers': [
      {
        'id': 'page-0',
        'type': 'paintContainer',
        'name': 'Page',
        'image': '',
        'children': []
      }
    ]
  })

  state.currentPainting = state.currentForm.paintings[state.currentForm.paintings.length-1]

  return FORM_SCHEMAS.update(state.currentSchemaId, state.currentForm)
}

调用 addNew 时,json 会正确更新数据

selectedObject getter如下

selectedObject: state => {
  var data = state.currentForm; var formControl = null

  if (state.selectedControlType === 'container') {
    if (state.creatorMode === 'painting') {
      return state.currentPainting.containers.find(container => container.id === state.selectedControlId)
    }
  }

  return null
}
}

请帮忙

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    这是 Vue 反应性问题。仅当对象更改时才会触发。在您的情况下,state.currentObject 仍然指向旧参考。

    您可以使用JSON.parse(JSON.stringify())进行深拷贝:

    state.currentObject.paintings.push({
      'config': {
        'formName': 'My New Picture',
        'orientation': 'portrait',
        'referenceNumber': '',
        'formType': ''
      },
      'id': (+new Date()),
      'containers': [
        {
          'id': 'page-0',
          'type': 'paintContainer',
          'name': 'Page',
          'image': '',
          'children': []
        }
      ]
    })
    state.currentObject = JSON.parse(JSON.stringify(state.currentObject))
    state.currentPainting = state.currentForm.paintings[state.currentForm.paintings.length-1]
    state.currentPainting = JSON.parse(JSON.stringify(state.currentPainting))
    

    更新: 你的吸气剂取决于state.currentPainting,而不是state.currentObject 我不确定 state.currentObject 和 state.currentPainting 之间有什么不同,但您需要更改 state.currentPainting 以使您的 getter 重新运行。

    【讨论】:

    • 那仍然行不通。我必须在网络上按 F5
    • 这就是问题所在。 currentPainting 在 currentObject 中
    【解决方案2】:

    使用 ...mapState 将您的数据与您的状态绑定,当您更改状态时,它会自动更新。

    【讨论】:

      猜你喜欢
      • 2019-07-30
      • 2020-08-04
      • 2021-03-20
      • 2019-06-08
      • 2020-09-12
      • 2022-01-22
      • 2020-02-10
      • 2021-06-19
      • 2019-01-25
      相关资源
      最近更新 更多