吸气剂在 vuex 中没有反应

问题描述

我定义了以下 store

 state: () => ({
    infoPackCreationData: null,infoPackCreationTab: null,}),getters: {
  infoPackImage(state: any) {
      return state.infoPackCreationTab && state.infoPackCreationTab.infopackContents
        ? state.infoPackCreationTab.infopackContents.filter((item: any) => item.type === "IMAGE")
        : [];
    }
},mutations: {
  setimageData(state:any,infopackImageData: any) {
      state.infoPackCreationTab.infopackContents.filter((item: any) => {if(item.type === "IMAGE")
      item = infopackImageData
        console.log(item,'this is items');
      return item})
    }
},actions: {
    setimageData(context: any,payload: any) {
      context.commit('setimageData',payload)
    }
}

在我的组件中,我使用 computed获取 imageList

  computed: {
      ...mapGetters("creationStore",["infoPackImage"]),imageList: {
        get() {
          return this.infoPackImage ?? [];
        },set(value) {
         this.$store.dispatch('creationStore/setimageData',value);
        }
      }
    },

问题是我想使用可拖动的库编辑 imageListindex 值, 但 imageList 并没有反应性,它只是移动图像而不显示一个索引中的另一个图像:

  async imageChange(e) {
        this.loading = true
        let newIndex = e.moved.newIndex;
        let prevOrder = this.imageList[newIndex - 1]?.order ?? 0
        let nextOrder = this.imageList[newIndex + 1]?.order ?? 0
        const changeImageOrder = new InfopackImageService();
        try {
          return await changeImageOrder.putimageApi(this.$route.params.infopackId,this.$route.params.tabId,e.moved.element.id,{
              title: e.moved.element.title,infopackAssetRef: e.moved.element.infopackAssetRef,order: nextOrder,prevIoUsOrder: prevOrder,}).then((res) => {
            let image = {}
            let infopackAsset = e.moved.element.infopackAsset
            image = {...res,infopackAsset};
            Vue.set(this.imageList,newIndex,image)
            this.loading = false
            return this.imageList
          });
        } catch (e) {
          console.log(e,'this is put error for tab change')
        }
      },

解决方法

Array.prototype.filter 不会就地修改数组,它返回一个新数组。所以这个突变永远不会改变任何状态:

mutations: {
  setImageData(state:any,infopackImageData: any) {
      state.infoPackCreationTab.infopackContents.filter((item: any) => {if(item.type === "IMAGE")
      item = infopackImageData
        console.log(item,'this is items');
      return item})
    }
},

因此,如果您打算更改 state.infoPackCreationTab.infopackContents,则需要分配 filter() 的结果:

mutations: {
  setImageData(state:any,infopackImageData: any) {
      state.infoPackCreationTab.infopackContents = state.infoPackCreationTab.infopackContents.filter(...)

然而,由于 state.infoPackCreationTab 在初始化期间没有 infopackContents 属性,除非您使用 Vue.set() 或只是替换整个 {带有新对象的 {1}} 对象(请参阅:Vuex on reactive mutations):

infoPackCreationTab