在Vuex模块中进行继承的方法 [英] Way to make inheritance in Vuex modules
问题描述
我正在使用VueJS和Vuex构建我的应用程序,当我有多个使用相同数据字段的模块时,我遇到了问题.它与dat之类的API配置有关.
Im building my app with VueJS and Vuex and I'm facing the issue when I have Multiple modules using the same data fields. Its about API configuration like dat.
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);
})
},
其他模块中的另一个功能就像
And another function in other Modules is like
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);
})
},
我想知道是否可以继承我的模块并在其中添加其他数据字段/函数?
I would like to know if I can just inheritence my Module and add additional datafields / functions in there?
我的每个模块都会有消息和状态字段,这些消息和状态字段是我对API的响应.
My every module would have message and status field which I getting in response of my 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];
}
}
}
就是这样.
有没有一种方法可以编写一次此代码,并在每个Im使用的模块中使用它?
Is there a way to write this code once and have it in every module Im using?
已
我什至无法在其中获得该apiParse函数,我需要对这些字段进行更改.但是,一直重复下去是没有意义的……有什么建议吗?
I even cant get this apiParse function in there, I need to make muttation for those fields. But repeting it all time is pointless... Any advices?
推荐答案
我将可重用的vuex代码放在小类中.例如.
I put my reusable vuex code in small classes. E.g.
crud.js
crud.js
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*
};
}
}
然后我可以在所有模块中使用它:
Then I can use it in all of my modules:
user.module.js
user.module.js
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
};
这篇关于在Vuex模块中进行继承的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!