• vue3对vuex的使用(对比vue2)


    Ⅰ.导入

     npm  i  vuex   --save
     ---------------------------
     import  Vuex  from  'vuex'
     Vue.use(Vuex);
    
    • 1
    • 2
    • 3
    • 4

    注意:

    版本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分块
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    简单使用:

    import {useStore} from 'vuex'
    export default {
    	setup(){
    		const store  = useStore();
    		console.log(store.state.name);    //获取
    		store.commit("getname", 12345);  //修改
    		store.dispatch("getnameAsync", 12345);  //修改
    	}
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    Ⅲ.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: {}
    })
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

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

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

    第二种 : ( 直接解构出来 ,可以省去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()
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

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

  • 相关阅读:
    Python实战:读取MATLAB文件数据(.mat文件)
    百篇博客 · 千里之行
    NtyCo纯C协程的原理分析
    python办公自动化系列之金蝶K3(三)
    虚拟人产业面临的挑战
    pygame中self有点想问的问题
    source insight context window不能显示上下文的问题
    大一作业HTML网页作业:中华传统文化题材网页设计5页(纯html+css实现)
    OkHttpClient实例
    密码安全:保护你的数据不被入侵的重要性
  • 原文地址:https://blog.csdn.net/weixin_42232622/article/details/125451861