關於在vue3中使用vuex與在vue2中使用vuex的區別


首先vue2中vuex版本是4.x以下,vue3中使用vuex需要保證vuex版本在4.x及以上。

以下說一說怎么在vue3中使用vuex,與vue2大同小異

首先在views新建一個store文件夾,寫index.js(這里只寫demo,所以不分模塊了。只做展示使用)

import { createStore } from 'vuex'

// 創建一個新的 store 實例
const store = createStore({
  state () {
    return {
      count: 0
    }
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})
export { store }

在main.js中注冊

import { createApp } from 'vue'
import App from './App.vue'


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

在組件類使用

<template>
  <div>{{ count }}</div>
  <div @click="change">觸發更新</div>
</template>

<script>
import { useStore } from 'vuex'
import { computed } from 'vue'
export default {
  name: 'login',
  setup () {
    const store = useStore()
    console.log('store',store.state.count)
    const change = () => {
      console.log('觸發更新')
      store.commit('increment')
    }
    return {
      // 在 computed 函數中訪問 state
      count: computed(() => store.state.count),
      change
    }
  }
};
</script>

<style scoped>

</style>

完成!!!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM