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

vue store作用

作者:自然ㄣ之光   发布日期:2026-06-16   浏览:130

// 定义一个 Vuex store
const store = new Vuex.Store({
  // state 是 Vuex 的状态树,包含应用的共享状态
  state: {
    count: 0
  },
  // mutations 是用于修改 state 的唯一方式,必须是同步函数
  mutations: {
    increment (state) {
      state.count++
    }
  },
  // actions 类似于 mutations,但可以包含异步操作
  actions: {
    incrementAsync ({ commit }) {
      setTimeout(() => {
        commit('increment')
      }, 1000)
    }
  },
  // getters 用于从 state 中派生出一些状态,类似于 Vue 组件中的 computed 属性
  getters: {
    doubleCount: state => state.count * 2
  }
})

// 在组件中使用 store
new Vue({
  el: '#app',
  store,
  computed: {
    // 访问 Vuex store 中的状态
    count () {
      return this.$store.state.count
    },
    // 访问 Vuex store 中的 getter
    doubleCount () {
      return this.$store.getters.doubleCount
    }
  },
  methods: {
    // 触发 Vuex store 中的 mutation
    increment () {
      this.$store.commit('increment')
    },
    // 触发 Vuex store 中的 action
    incrementAsync () {
      this.$store.dispatch('incrementAsync')
    }
  }
})

解释说明:

  • Vuex Store 是 Vue 应用的状态管理库,它提供了一个集中式的存储来管理所有组件的状态。
  • state 用来存储应用的共享状态。
  • mutations 是更改 state 的唯一途径,且必须是同步函数。
  • actions 用于处理异步操作,并最终提交 mutation 来更改 state。
  • getters 用于从 state 中派生出一些状态,类似于 Vue 组件中的计算属性。
  • 在组件中,可以通过 this.$store 来访问和操作 Vuex store。

上一篇:全局安装vue

下一篇:nginx部署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 中文站