vue3对vuex的使用(对比vue2)

Ⅰ.导入

 npm  i  vuex   --save
 ---------------------------
 import  Vuex  from  'vuex'
 Vue.use(Vuex);

注意:

版本 vuex
vue2 要用vuex 3 版本
vue3 要用vuex 4 版本

Ⅱ.vue 3 使用 vuex

创建store仓库: /store/index.js

import { createStore } from 'vuex';
export default createStore({
state: {name: 123 },
mutations:{    getname(state,newVal){this.state.name=newVal;}  }, 
//同步方法:(只有mutations才能改state的值)
actions:{   getnameAsync(){ ... }     },  //异步方法
geeter:{},  //相当于计算属性
modules: {}  //将vuex分块
})

简单使用:

import {useStore} from 'vuex'
export default {
	setup(){
		const store  = useStore();
		console.log(store.state.name);    //获取
		store.commit("getname", 12345);  //修改
		store.dispatch("getnameAsync", 12345);  //修改
	}

}

Ⅲ.vue 2 使用 vuex

创建store仓库: /store/index.js

export default  new  Vuex.Store({
state:{count :  0},           //存储变量                                         
mutations: {add(state,step){  state.conut+=step; }},   //存储方法
actions: {addAsync(){...},//异步操作
geeter:{},  //相当于计算属性
modules: {}
})

vue2使用vuex的方法有2种写法:
第一种 : ( 通过this.$store获取 )

 this.$store.state.变量名
 this.$store.commit('add',1);
 this.$store.dispatch('addAsync',1);

第二种 : ( 直接解构出来 ,可以省去this.$store )

 import {mapState,mapMutations,mapActions} from 'vuex';    
 computed:{...mapState(['conut']);}    --->  count  可以直接使用{{conut}}
 methods:{
 	       ...mapMutations(['add']),    ---> button   可以直接使用 @onclick = add(1)
 	       ...mapActions(['addAsync']), ---> button   可以直接使用 @onclick = addAsync()
}

如果vue3觉得使用麻烦的话,可以试试更好用的 pinia 点击这里

你可能感兴趣的:(入坑vue3,javascript,前端)