vue3.x专题十 ---- vuex使用方法总结(全局状态)

1、创建vuex仓库  store/index.js

import { createStore } from 'vuex'
// 创建vuex仓库并导出
export default createStore({
  state: {
    // 数据
    username: '张三'
  },
  mutations: {
    // 改数据函数
    updateName (state) {
      state.username = “新名字”
    }
  },
  actions: {
    // 异步操作:请求数据函数
    updateName (context) {
      // 发请求
      setTimeout(() => {
        context.commit('updateName', '更改名字')
      }, 1000)
    }
  },
  modules: {
  },
  getters: {
    // vuex的计算属性
    newName (state) {
      return 'hello  ' + state.username
    }
  }
})

2、在组件中使用

<template>
  <div>
    使用根模块state数据:{{ $store.state.username }}
  </div>
  <div>
    使用根模块getters数据:{{ $store.getters.newName }}
  </div>
  <br>
  <div>
    <button @click="mutationsFn">mutationsFn改名字</button>
  </div>
  <div>
    <button @click="$store.commit('updateName', '李四')">mutationsFn改名字</button>
  </div>
  <br/>
  <br/>
  <div>
    <button @click="actionsFn">actionsFn改名字</button>
  </div>
  <div>
    <button @click="$store.dispatch('updateName')">actionsFn改名字</button>
  </div>
</template>

<script>
import { useStore } from 'vuex'
export default {
  name: 'App',
  setup (props) {
    const store = useStore()
    const mutationsFn = () => {
      // 执行根目录里面的mutations方法修改数据
      store.commit('updateName', '李四')
    }
    const actionsFn = () => {
      // 执行根目录里面的mutations方法修改数据
      store.dispatch('updateName')
    }
    return {
      mutationsFn,
      actionsFn
    }
  }
}
</script>
<style lang="less">

</style>

3、在单独的 js文件里面, 使用vuex

import { useStore } from 'vuex'
const store = useStore()
const mutationsFn = () => {
    // 执行根目录里面的mutations方法修改数据
    store.commit('updateName', '李四')
}
const actionsFn = () => {
    // 执行根目录里面的mutations方法修改数据
    store.dispatch('updateName')
}

这里做一下总结,下一节我们总结一下vuex分模块的状态,觉得有用的朋友,可以点赞评论收藏一哈。。。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值