Vue3 整合vuex
Vuex 4 引入了一个新的 API 用于在组合式 API 中与 store 进行交互。可以在组件的 setup
钩子函数中使用 useStore
组合式函数来检索 store
1.准备工作
-
1.1 安装
vue 3安装 vuex@4
npm install vuex@4 --S
-
1.2 配置
-
配置index.js
使用**
createStore
**创建import {createStore} from "vuex"; export default createStore({ state: {sum:1}, getters:{}, mutations: {}, actions: {}, modules: {} })
-
vue引入
import { createApp } from 'vue' import App from './App.vue' import store from "@/store"; const app = createApp(App); app.use(store); app.mount('#app')
-
2.使用
在这里会使用到useStore()
这个新的Api,它的作用就相当于$store
-
2.1 State
-
方法一:
在标签中直接使用
{{$store.state.name}}
方法二:
useStore取出
useStore取出 sum:{{ store.state.全局数据名称 }} setup() { let store = useStore(); return { store } }
方法三:
computed函数取出
computed取出 sum:{{ sum }} setup() { let store = useStore(); return { // 在 computed 函数中访问 state sum: computed(() => store.state.sum), store } },
-
-
2.2 Getter
-
方法一:
直接取出
$store直接取出 sum:{{ $store.getters.全局数据名称 }}
方法二:
利用computed取出
setup() { let store = useStore(); return { // 在 computed 函数中访问 getter double: computed(() => store.getters.doubleSum), store } }
-
-
2.3 Mutation
要使用 mutation 和 action 时,只需要在
setup
钩子函数中调用commit
和dispatch
函数。-
方法:
let store = useStore(); // 使用 mutation addSum:()=>{store.commit("addSum",1)},
-
-
2.4 Action
-
方法:
let store = useStore(); // 使用 action waitAdd:()=>{store.dispatch("waitAdd")},
-