vue组件通讯vuex状态管理例子

Vuex 是 Vue.js 的状态管理模式和库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。以下是一个简单的 Vuex 状态管理例子,展示如何在 Vue 组件中使用 Vuex 进行通讯。

首先,我们需要安装并引入 Vuex。如果你正在使用 Vue CLI 创建的项目,可以通过 npm 或 yarn 来安装:

bash

npm install vuex

# 或者

yarn add vuex

然后,我们可以在 Vue 应用中设置 Vuex:

store.js

javascript

import Vue from 'vue'

import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({

  state: {

    count: 0

  },

  mutations: {

    increment(state) {

      state.count++

    },

    decrement(state) {

      state.count--

    }

  },

  actions: {

    incrementAction({ commit }) {

      commit('increment')

    },

    decrementAction({ commit }) {

      commit('decrement')

    }

  },

  modules: {

    // 可以在这里添加其他模块

  }

})

接下来,在 Vue 应用的主入口文件(通常是 main.js 或 main.ts)中引入并使用 Vuex store:

main.js

javascript

import Vue from 'vue'

import App from './App.vue'

import store from './store'

new Vue({

  store,

  render: h => h(App),

}).$mount('#app')

现在,我们可以在 Vue 组件中使用 Vuex:

Counter.vue

vue

<template>

  <div>

    <p>Count: {{ count }}</p>

    <button @click="increment">Increment</button>

    <button @click="decrement">Decrement</button>

  </div>

</template>

<script>

export default {

  computed: {

    count() {

      return this.$store.state.count

    }

  },

  methods: {

    increment() {

      this.$store.commit('increment')

      // 或者使用 action

      // this.$store.dispatch('incrementAction')

    },

    decrement() {

      this.$store.commit('decrement')

      // 或者使用 action

      // this.$store.dispatch('decrementAction')

    }

  }

}

</script>

在上面的 Counter.vue 组件中,我们使用了计算属性 count 来从 Vuex store 中获取 count 的值。我们还定义了两个方法 increment 和 decrement,它们分别通过调用 Vuex store 中的 commit 方法来触发 mutations 中的 increment 和 decrement 函数。

你也可以选择使用 actions 而不是直接调用 mutations,因为 actions 允许你包含任意异步操作。在上面的例子中,我已经注释了使用 actions 的代码,你可以取消注释来查看如何使用它们。

这样,我们就实现了一个简单的 Vuex 状态管理例子,在 Vue 组件之间共享了状态 count。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值