vue3中vuex的使用——vue2和vue3的基础用法对比第三篇

vue2.0用法

/* vue2.0 */                         
import Vue from 'vue'                
import Vuex from 'vuex'
Vue.use(Vuex)
let store = new Vuex.Store(省略)
export default store    

vue3.0用法

/* vue3.0 */                         
import { createStore } from 'vuex'
const store = createStore(省略)
export default store

 vue2.0和vue3.0只是引用、调用vuex的方式改变了,定义是一样的没有改变(即忽略部分是一样的)

以下为省略部分

{
  // 数据
  state:{count:1},
  // 可以认为是 store 的计算属性computed。调用方式:
// vue2方式:this.$store.getters.increment
// vue3方式:(1)proxy.$store.getters.increment
//(2)const store = useStore(); store.getters.increment
  getters:{
    increment (state) {
      return state.count
    }
  },
  // 同步请求。调用方式:
// vue2方式:this.$store.commit("increment",{data:1})
// vue3方式:(1)proxy.$store.commit("increment",{data:1})
// (2)const store = useStore(); store.commit("increment",{data:1})
  mutations:{
    // state 作为第一个参数
    increment (state,{data}) {
      state.count=data
    }
  }, // 异步请求。调用方式:
// vue2方式:this.$store.dispatch("increment",{data:1})
// vue3方式:(1)proxy.$store.dispath("increment",{data:1})
// (2)const store = useStore(); store.dispatch("increment",{data:1})
  actions:{
    increment(data){
      console.log(data)
    }
  },
  // 模块化,将前4个模块封装写在这里面
  
modules:{}
}

 

作者:博客园-DDjans,转载时请注明来源。

(请勿将文章用在任何商业用途,违者将承担相应法律责任)

 

posted @ 2021-08-19 11:58  DDjans  阅读(666)  评论(0编辑  收藏  举报