我正在用VueJS和Vuex构建我的应用程序,当我有多个模块使用相同的数据字段时,我会面临这个问题.它是关于像dat这样的API配置的.

getUsers ({ state, commit }) {
    axios.get(urls.API_USER_URL).then( response => {
        let data = response.data;
        parseApi(state, data, 'user');

    }).catch( err => {
        console.log('getUser error: ', err);
    })
},

在另一个功能模块中

getPosts ({ state, commit }) {
    axios.get(urls.API_POST_URL).then( response => {
        let data = response.data;
        parseApi(state, data, 'posts');

    }).catch( err => {
        console.log('getUser error: ', err);
    })
},

我想知道我是否可以继承我的模块并在其中添加额外的数据字段/函数?

我的每个模块都会有消息和状态字段,这些字段是我根据API得到的响应.

export default {
    state : {
        message : "",
        status : 0
    },
    parseApi: function(state, data, property) {
        if (data.hasOwnProperty('message')) {
            state.message = data.message;
        }
        if (data.hasOwnProperty('status')) {
            state.status = data.status;
        }
        if (data.hasOwnProperty(property)) {
            state[property] = data[property];
        }
    }
}

应该是这样的.

有没有一种方法可以把这段代码写一次,然后放到我使用的每个模块中?

编辑:

我甚至不能在那里得到这个apiParse函数,我需要为那些字段发牢骚.但是一直重复它是没有意义的...有什么建议吗?

推荐答案

我将可重用的vuex代码放在小班中.例如.

100

export default class {
    constructor ( endpoint ) {
       this.state = {
          endpoint: endpoint,
          meta:     {},
          status:   null,
          known:    [],
          currentId: null,
       };
       this.getters = {
          id: state => id => state.known.find( o => o.id === id )
       };
       this.actions = {
          async store( context, payload ) {
               *(call to API)*
          },
          async update( context, payload ) {
               *(call to API)*
          },
          *...etc*
      };
      this.mutations = {
         STORED(state, item) {
            state.known.push(item);
         },
         *...etc*
      };
   }
}

然后我可以在我的所有模块中使用它:

100

import Crud from '/crud';
var crud = new Crud('/api/users');

const state = {
   ...crud.state,
};
const getters = {
   ...crud.getters,
};
const actions = {
   ...crud.actions,
};
const mutations = {
   ...crud.mutations,
};

export default {
   namespaced: true,
   state,
   getters,
   actions,
   mutations
};

Vue.js相关问答推荐

检测Vue3/Vue-test-utils中的Vuex还原/Mutations

如何使用composition api v-model Select 框获取其他JSON 值?

过渡如何在 Vue JS 3 中的图像上工作?

如何向 添加方法和 v-model?

混合使用 React 和 Vue 是个好主意吗?

Vuetify grid layout - 如何填充网格中元素的高度

vue.js 在 App.vue 中获取路由名称

Vue.js 中的 mount挂载是什么意思?

为什么组件在 v-if 下没有被销毁

VueJS + VueRouter:有条件地禁用路由

将 props 传递给 Vue 组件中的元素属性

将数据传递给另一条路由上的组件

如何从 .vue 文件中导出多个对象

axios.patch / axios.put 在 Vue 和 Laravel 中不起作用

Vue.js 处理多次点击事件

如何在 Vue 类组件中定义过滤器?

如何在两个属性上使用 Vue/Vuetify 自动完成过滤器?

输入文件 Select 事件在 Select 同一文件时未触发

隐藏特定标题及其在 vuetify 数据表中的对应列

在另一个 props 的验证器中访问 props 值