vue3 中 vuex 两种方法使用 使用用用用用用用用

今天 来写一下 这个vue3中vuex的用法

1.安装

npm install vuex -S

2.引入

这个时候就有两种选择了  

第一种

直接引入store文件

import $store from './store'

第二种

引入 vuex4.x 的 useStore 方法

import { useStore } from 'vuex'

3.世纪使用

/store/index.js

import { createStore } from 'vuex'

export default createStore({
  state: {
    data: 123
  },
  mutations: {
    setData: (state, val) => {
      state.data = val
    }
  },
  actions: {
    setDataAct: ({ commit }, val) => {
      commit('setData', val)
    }
  },
  modules: {
  }
})

第一种   

直接引入store文件 的使用

import $store from './store'

export default {
  setup() {
    onMounted(() => {
      console.log($store.state.data); //123
    });
  },
};

也可以对mutations 和 actions 进行操作 如:

setup() {
    onMounted(() => {
      console.log($store.state.data); //123
      // dispatch 调用 actions
      $store.dispatch("setDataAct", 345);
      console.log($store.state.data); //345
      // commit 调用 mutations
      $store.commit("setData", 456);
      console.log($store.state.data); //456
    });
  },

第二种

使用 vuex 的 useStore 

import { useStore } from 'vuex'

export default {
  setup() {
    const $store = useStore()
    onMounted(() => {
      console.log($store.state.data); //123
    });
  },
};

对mutations 和 actions 进行操作:

setup() {
    const $store = useStore()
    onMounted(() => {
      console.log($store.state.data); //123
      // dispatch 调用 actions
      $store.dispatch("setDataAct", 345);
      console.log($store.state.data); //345
      // commit 调用 mutations
      $store.commit("setData", 456);
      console.log($store.state.data); //456
    });
  },

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值