学习笔记:vuex(4.x)

899 阅读1分钟

开头

  • 个人笔记,文章有问题请提出,我会在第一时间进行修复!

正文

创建方式
  • createStore
  • 用来创建store对象
  • 4.x用法
import { createStore } from "vuex"
const store = createStore({
    // options
    .....
})
  • 3.x用法
import Vuex from "vuex"
const router = new Vuex.store({
    // options
    ......
})

挂载方式

  • 因为vue3的composition api,vuex的挂载方式以插件来挂载
  • 4.x的用法
    import { createApp } from 'vue'
    import store from './store.js'
    import App from './App.vue'
    createApp(App).use(store).mount('#app');
  • 3.x的用法,以属性的方式进行挂载
 import store from './store.js'
   new Vue({
      store
   })

组件中的使用

  • 因为setup中不能访 this,所以提供一个api来获取 store ———— useStore()
  • 4.x的用法
   import { useStore } from "vuex"
   export default({
      setup(){
        const store = useStore();
        const changeNum = ()=>{
            const { num } = store.getters;
            store.dispatch("CHANGE_NUM",num ++);
        }
        return{
            changeNum
        }
      }
   })
  • 3.x的用法
    export default({
       methods:{
           changeNum(){
               const { num } = this.$store.getters;
               this.$store.dispatch('CHANGE_NUM',num++)
           }
       }
    })