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

vue3 使用vuex

作者:逐鹿↘星恒   发布日期:2026-06-24   浏览:63

// store.js
import { createStore } from 'vuex'

// 创建一个新的 store 实例
const store = createStore({
  state () {
    return {
      count: 0
    }
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment ({ commit }) {
      commit('increment')
    }
  },
  getters: {
    count: state => state.count
  }
})

export default store

// main.js
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'

const app = createApp(App)
app.use(store)
app.mount('#app')

// 在组件中使用 Vuex
<template>
  <div>
    <p>{{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

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

export default {
  computed: {
    ...mapState(['count'])
  },
  methods: {
    ...mapActions(['increment'])
  }
}
</script>

解释说明:

  1. 创建 Vuex Store:

    • createStore 是 Vue 3 中用于创建 Vuex Store 的函数。
    • state 定义了应用的状态,这里定义了一个 count 变量,初始值为 0。
    • mutations 用于定义修改状态的方法。这里的 increment 方法会将 count 增加 1。
    • actions 类似于 mutations,但它们主要用于处理异步操作。这里定义了一个 increment action 来调用 mutation。
    • getters 用于从 state 中派生出一些状态,例如对 state 进行过滤、计算等。
  2. 在主文件中引入并使用 Vuex:

    • createApp 是 Vue 3 中用于创建应用实例的函数。
    • 使用 app.use(store) 将 Vuex Store 注入到 Vue 应用中。
  3. 在组件中使用 Vuex:

    • 使用 mapStatemapActions 辅助函数可以更方便地访问 Vuex 中的状态和方法。
    • computed 中的 ...mapState(['count'])count 映射为组件的计算属性。
    • methods 中的 ...mapActions(['increment'])increment 映射为组件的方法。

通过以上代码和解释,你应该能够理解如何在 Vue 3 中使用 Vuex 管理应用的状态。

上一篇:vue关闭eslint

下一篇:teleport vue

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

vue.js 3

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js devserv

vue.config.js configu

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

Laravel 中文站