state的用法:书写和读取
Vuex书写:state: { count: 0 },
前端读取:computed: { ...mapState(['count’])}
getters的用法:书写和读取
Vuex书写:
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
第二种
getters: {
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
前端读取:
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
])
}
mution的用法:改变state和触发方式
改变state:
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
// ...
[RECEIVE_ADDRESS] (state, {address}) {
state.address = address
},
在action中触发
// 异步获取食品分类列表
async getCategorys({commit}) {
// 发送异步ajax请求
const result = await reqFoodCategorys()
// 提交一个mutation
if (result.code === 0) {
const categorys = result.data
commit(RECEIVE_CATEGORYS, {categorys})
}
},
action的用法:书写action函数,前端触发
action函数
// 异步获取地址
async getAddress({commit, state}) {
// 发送异步ajax请求
const geohash = state.latitude + ',' + state.longitude
const result = await reqAddress(geohash)
// 提交一个mutation
if (result.code === 0) {
const address = result.data
commit(RECEIVE_ADDRESS, {address})
}
},
前端触发
this.$store.dispatch('incrementAsync', {
amount: 10
})
modules中使用这些方法
import { mapState, mapActions } from "vuex";
export default {
methods: {
...mapActions("moduleA", [
"sampleFn" // -> this.sampleFn()
]),
clickFn() {
this.$store.dispatch("moduleA/sampleFn"); // 直接从store中dispatch
}
}
};
// 计算属性
computed: {
...mapState("addCourseware", {
// TODO: 变量什么意思可以去vuex中add-course-ware.js文件看
evalList: (state) => state.evalList,
}),
...mapGetters("addCourseware", ["isDoneList"]),
},