我继承了一个用打字稿编写的VueJs项目。我有一个显示一些数据的组件,Vuex存储通过一个突变(ADD_SCHOOL)更新,但更改未反映在视图中。我猜想我需要某种监视程序,但是我不确定该怎么做才能使Vue对我的商店中的更改做出反应。
查看
data() {
return {
school: {} as ISchool
};
},
async mounted() {
await this.getSchoolInformation();
},
methods: {
async getSchoolInformation() {
this.school = await Stores.schoolStore.getSchool(1);
}}}
Store.ts
Vue.use(Vuex);
const modules: ModuleTree<IRootState> = {
schoolStore: schoolModule
};
const store: Store<IRootState> = new Store<IRootState>({
modules
});
导出默认存储;
SchoolStore.ts
export default class SchoolStore {
public async getSchool(id: number, isFirstLoad: boolean): Promise<ISchool> {
return Store.getters[SchoolNamespace + GetterTypes.GET_SCHOOL_FROM_STORE];
}
}
School Modules.ts
export const state: ISchoolState = {
schools: []
};
export const getters: GetterTree<ISchoolState, IRootState> = {
[GetterTypes.GET_SCHOOL_FROM_STORE]: state => {
const storeSchool: ISchool | undefined = state.schools.find(x => x.id === 1);
return storeSchool as ISchool;
}
};
export const mutations: MutationTree<ISchoolState> = {
[MutationTypes.ADD_SCHOOL](state: ISchoolState, school: ISchool): void {
const index: number = state.schools.findIndex(x => x.id === school.id);
if(index === -1) {
state.schools.push(school);
} else {
state.schools.splice(index, 1, school);
}}};
const schoolModule: Module<ISchoolState, IRootState> = {
actions,
getters,
mutations,
namespaced: true,
state
};
export default schoolModule;
Index.ts
const schoolStore: SchoolStore = new SchoolStore();
export default {
schoolStore
};
答案 0 :(得分:1)
多亏了Ackroydd,我通过在视图中简单地使用计算属性来使他工作-我还使getSchool同步了
更新后的视图
computed: {
school() {
return Stores.schoolStore.getSchool(1, false);
}
}
});
答案 1 :(得分:0)
文档中描述了您遇到的这个问题:reactivity in depth
在您进行突变时,您要更新数组中的项目或向数组中添加新项目。 Vue不会接受该更改。为此,您需要使用Vue.set
:
import Vue from 'vue'
...
if(index === -1) {
Vue.set(state.schools, state.schools.length, school);
} else {
Vue.set(state.schools, index, school);
}}};