今天 来写一下 这个vue3中vuex的用法
1.安装
npm install vuex -S
2.引入
这个时候就有两种选择了
第一种
直接引入store文件
import $store from './store'
第二种
引入 vuex4.x 的 useStore 方法
import { useStore } from 'vuex'
3.世纪使用
/store/index.js
import { createStore } from 'vuex'
export default createStore({
state: {
data: 123
},
mutations: {
setData: (state, val) => {
state.data = val
}
},
actions: {
setDataAct: ({ commit }, val) => {
commit('setData', val)
}
},
modules: {
}
})
第一种
直接引入store文件 的使用
import $store from './store'
export default {
setup() {
onMounted(() => {
console.log($store.state.data); //123
});
},
};
也可以对mutations 和 actions 进行操作 如:
setup() {
onMounted(() => {
console.log($store.state.data); //123
// dispatch 调用 actions
$store.dispatch("setDataAct", 345);
console.log($store.state.data); //345
// commit 调用 mutations
$store.commit("setData", 456);
console.log($store.state.data); //456
});
},
第二种
使用 vuex 的 useStore
import { useStore } from 'vuex'
export default {
setup() {
const $store = useStore()
onMounted(() => {
console.log($store.state.data); //123
});
},
};
对mutations 和 actions 进行操作:
setup() {
const $store = useStore()
onMounted(() => {
console.log($store.state.data); //123
// dispatch 调用 actions
$store.dispatch("setDataAct", 345);
console.log($store.state.data); //345
// commit 调用 mutations
$store.commit("setData", 456);
console.log($store.state.data); //456
});
},