Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue3中vuex的使用

作者:掌心余温   发布日期:2025-11-07   浏览:71

// store.js

// 引入 Vuex 和 Vue
import { createStore } from 'vuex'

// 创建一个新的 store 实例
const store = createStore({
  state () {
    return {
      // 定义状态,这里是一个计数器
      count: 0
    }
  },
  mutations: {
    // 提交更改,同步事务
    increment (state) {
      state.count++
    }
  },
  actions: {
    // 触发更改,可以包含异步操作
    incrementAsync ({ commit }) {
      setTimeout(() => {
        commit('increment')
      }, 1000)
    }
  },
  getters: {
    // 获取状态,类似于计算属性
    doubleCount (state) {
      return state.count * 2
    }
  }
})

export default store

// main.js

// 引入 Vue 和 Vuex 的 store
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'

// 创建 Vue 应用并挂载 store
createApp(App).use(store).mount('#app')

// 在组件中使用 Vuex

<template>
  <div>
    <!-- 显示当前的 count -->
    <p>{{ count }}</p>
    <!-- 按钮触发 mutations -->
    <button @click="increment">Increment</button>
    <!-- 按钮触发 actions -->
    <button @click="incrementAsync">Increment Async</button>
    <!-- 显示通过 getter 计算后的值 -->
    <p>{{ doubleCount }}</p>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'

export default {
  computed: {
    // 将 state 中的 count 映射到局部计算属性
    ...mapState(['count']),
    // 将 getter 中的 doubleCount 映射到局部计算属性
    ...mapGetters(['doubleCount'])
  },
  methods: {
    // 将 mutations 中的 increment 映射到局部方法
    ...mapMutations(['increment']),
    // 将 actions 中的 incrementAsync 映射到局部方法
    ...mapActions(['incrementAsync'])
  }
}
</script>

这段代码展示了如何在 Vue 3 中使用 Vuex 来管理应用的状态。它包括创建一个 Vuex store,定义状态、mutations、actions 和 getters,并在 Vue 组件中使用这些功能。

上一篇:vue2 filters

下一篇:nodejs vue

大家都在看

vue.js devtools用法

vue js for循环

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js configu

node.js vue

vue3组件传值的方式

vue3 子路由

vue3 router传参

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站