Vue3.0 Vuex传值

本文介绍如何在Vue3.0项目中利用Vuex进行组件间的数据传递和状态管理,通过创建store/index.ts文件配置Vuex store,然后在view/home和view/about视图中使用store中的状态和方法。
摘要由CSDN通过智能技术生成

1.store/index.ts

import { createStore } from 'vuex'
export default createStore({
  state: {
    name: '默认值'
  },
  mutations: {
    setState(state, args) {
      state.name = args
    }
  },
  actions: {
    setStateName({ commit }, args) {
      commit('setState', args)
    }
  },
  getters: {
    getState(state) {
      return state.name
    }
  },
  modules: {
  }
})

2.view/home

<template>
  <div class="home">
    <div><button @click="FnSetStateName">给about传值</button></div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { useStore } from "vuex";
export default defineComponent({
  name: "Home",
  setup() {
    const store = useStore();
    const FnSetStateName = function () {
      //Action 通过 store.dispatch 方法触发
      store.dispatch("set
Vue中使用Vuex进行状态管理是非常常见的,它可以帮助我们更好地组织和管理应用程序的状态。下面是一个简单的例子,演示如何在Vue中使用Vuex进行传值。 1. 安装Vuex 首先,我们需要安装Vuex。可以使用npm或yarn来安装: ``` npm install vuex --save ``` 或者 ``` yarn add vuex ``` 2. 创建store 在Vue中使用Vuex需要先创建一个store。在store中,我们可以定义和管理应用程序的所有状态。 ``` import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++ } } }); export default store; ``` 在这个例子中,我们定义了一个名为“count”的状态和一个名为“increment”的mutation,当我们调用“increment”mutation时,它会增加“count”状态的值。 3. 在Vue组件中使用store 现在我们已经创建了一个store,接下来让我们在Vue组件中使用它。我们需要使用Vuex提供的“mapState”和“mapMutations”辅助函数来访问store中的状态和mutations。 ``` <template> <div> <h1>{{ count }}</h1> <button @click="increment">Increment</button> </div> </template> <script> import { mapState, mapMutations } from 'vuex'; export default { computed: { ...mapState(['count']) }, methods: { ...mapMutations(['increment']) } } </script> ``` 在这个例子中,我们使用了“mapState”辅助函数来将“count”状态映射到组件的计算属性中,并使用“mapMutations”辅助函数将“increment”mutation映射到组件的方法中。这样,在组件中就可以直接使用“count”状态和“increment”mutation了。 以上就是使用Vuex进行状态管理的基本过程。在实际开发中,我们通常需要定义更多的状态和mutations,并使用actions和getters等高级特性来管理更复杂的状态。但基本的使用方法和原理都是相似的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值