vue3中vuex的变化

一. 挂载store的方式不同

vue2的方式:

new Vue({
    
    
  render: h => h(App),
  router,
  store,
  i18n
}).$mount('#app')

vue3的方式:

createApp(App).use(store).mount('#app')

二. 创建store实例方式的不同

vue2:

const  store = new Vuex.Store({
    
    
        ....
})

vue3:

函数式创建(新的vue-router实例也是函数式创建)

import {
    
     createStore } from 'vuex'

export default createStore({
    
    
  state: {
    
    
  },
  getters: {
    
    
  },
  mutations: {
    
    
  },
  actions: {
    
    
  },
  modules: {
    
    
  }
})

三:使用方式

vue3和vue2的方式基本相同:

  mutations: {
    
    
    addCount(state,payload) {
    
    
      if(payload) {
    
    
        state.count = payload.count
      } else {
    
    
        state.count += 1 
      }
    }
  },
  actions: {
    
    
    addCountAsync(context,payload) {
    
    
      return new Promise(resolve => {
    
    
        context.commit('addCount',payload)
        resolve()
      })
    }
  },


  mounted() {
    
    
    console.log(this.$store.state.count)  //10
    setTimeout(() => {
    
    
      this.$store.dispatch('addCountAsync',{
    
    count: 19}).then(() => {
    
    
        console.log(this.$store.state.count) // 19
        console.log('成功了修改了count值')
      })
    },1000)
  }

两种导入方法:
a.可以通过函数式的方式引入 useStore
b. 导入的方式 @/store/.index.js

// 函数式导入方式
import {
    
     useStore } from 'vuex'
export default {
    
    
  name: 'HelloWorld',
  props: {
    
    
    msg: String
  },
  setup() {
    
    
    console.log(useStore())
    console.log(useStore().state.count)
  },

如果这里要使html上的模板更新:
a. reactive 变为响应式数据
b. computed 使count 变为计算属性

  setup() {
    
    
    console.log(useStore())
    console.log(useStore().state.count)
    return reactive({
    
    
      count: computed(() => useStore().state.count) 
    }) 
  },

四:debugger

新的vuex的debugger:

// 导入createLogger
import {
    
     createLogger, createStore } from 'vuex'

// 只在开发环境生效
const debug = process.env.NODE_ENV !== 'production'

export default createStore({
    
    
  state: {
    
    
    count: 10
  },
  getters: {
    
    

  },
  mutations: {
    
    
    addCount(state,payload) {
    
    
      if(payload) {
    
    
        state.count = payload.count
      } else {
    
    
        state.count += 1 
      }
    }
  },
  actions: {
    
    
    addCountAsync(context,payload) {
    
    
      return new Promise(resolve => {
    
    
        context.commit('addCount',payload)
        resolve()
      })
    }
  },
  modules: {
    
    
  },
  // 插件注入,只在开发环境生效
  plugins: debug ? [createLogger()] : []
})

日志打印:

在这里插入图片描述

总结:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_39549013/article/details/126344175