Vue3 整合vuex

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 钩子函数中调用 commitdispatch 函数。

    • 方法:

      let store = useStore();
      // 使用 mutation
      addSum:()=>{store.commit("addSum",1)},
      
  • 2.4 Action

    • 方法:

      let store = useStore();
      // 使用 action
      waitAdd:()=>{store.dispatch("waitAdd")},
      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LvhaoIT

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值