1、安装
npm install vuex@next --save
2、引入注册
store.js
import { createStore } from 'vuex'
const store = createStore({
state: { num: 0 }
...
})
export default store
main.ts
import { createApp } from 'vue'
import App from './App.vue'
import routes from "./routes"
import store from "./store"
const app = createApp(App)
// 挂载路由
app.use(routes)
app.use(store)
app.mount('#app')
3、mapState,mapGetters,mapMutations,mapActions
先引入
import { mapState,mapGetters,mapMutations,mapActions} from 'vuex'
1.mapState
nickname(){return this.$store.state.nickname}
age(){return this.$store.state.age}
gender(){return this.$store.state.gender}
//一句代替上面三句
computed: mapState(['nickname','age','gender'])//映射哪些字段就填入哪些字段
当还有自定义计算属性时
computed: { //computed是不能传参数的
value(){
return this.val/7
},
...mapState(['nickname','age','gender'])
}
2.mapGetters
computed: { //computed是不能传参数的
valued(){
return this.value/7
},
...mapGetters(['realname','money_us'])
}
3.mapMutations
methods:{
...mapMutations(['addAge'])
//就相当于
addAge(payLoad){
this.$store.commit('addAge',payLoad)
}
}
4.mapActions
methods:{ ...mapActions([‘getUserInfo’])}
总结一下:
- 依赖state得到新的数据,用getters(跟computed一样,只读)
- 修改state的属性值,就用mutations(同步操作)
- 异步就用actions
4、使用
store.js
import { createStore, Store } from 'vuex'
import { ComponentCustomProperties } from 'vue';
declare module '@vue/runtime-core' {
interface State {
num: number,
str: string,
arr: string[]
}
interface ComponentCustomProperties {
$store: Store<State>
}
}
const store = createStore({
state() {
return {
num: 12,
str: 'tom',
arr: [1, 2, 4],
}
},
mutations: {
numMutation(state: any, data: number) {
state.num = data;
},
strMutation(state: any, data: string) {
state.str = data;
},
arrMutation(state: any, data: string[]) {
state.arr = data;
},
},
actions: {
numAction({ commit }, args) {
commit('numMutation', args)
}
},
modules: {
}
})
export default store
home.vue
<template>
<div class="home">我是子组件home</div>
-------------{{ num }}
<button @click="numAction(10)">change</button>
</template>
<script lang="ts" >
import { toRef, toRefs, defineComponent } from "vue";
import { useStore } from "vuex";
export default defineComponent({
name: "home",
setup() {
const store: any = useStore();
//mapState
const { str, arr, obj } = toRefs(store.state);
const num = toRef(store.state, "num");
//mapGetters
const { getNum } = toRefs(store.getters);
//mapMutations
const {
strMutation: [strMutation],
} = store._mutations;
//mapActions
const {
numAction: [numAction],
} = store._actions;
return {
str,
num,
arr,
obj,
getNum,
strMutation,
numAction,
};
},
methods: {},
});
</script>
<style scoped>
</style>