vue2 - vuex 状态管理工具

1.什么是vuex 状态管理工具

vuex是适用于在Vue项目开发时使用的状态管理工具。试想一下,如果在一个项目开发中频繁的使用组件传参的方式来同步data中的值,一旦项目变得很庞大,管理和维护这些值将是相当棘手的工作。为此,Vue为这些被多个组件频繁使用的值提供了一个统一管理的工具——VueX。在具有VueX的Vue项目中,我们只需要把这些值定义在VueX中,即可在整个Vue项目的组件中使用。

  • state 存放状态
  • mutations state成员操作
  • getters 加工state成员给外界
  • actions 异步操作
  • modules 模块化状态管理

2.安装vuex

npm install vuex

 

3.定义moon.js文件 (/src/store/moon.js)

import Vue from 'vue'
//引入vuex
import Vuex from 'vuex'
//使用vuex插件
Vue.use(Vuex)

//异步操作
let actions={
  setName(context,value){
    context.commit('SETNAME',value)
  }
}
//state成员操作
let mutations={
  SETNAME(state,value){
    state.name=value
  }
}
//加工state成员给外界
let getters={
  bigValue(state){
    return state.balance*10
  }
}
//state 存放状态
let state={
  name: 'levi',
  balance: 100,
  bodyObj: {
    food: 'pizza',
  }
}

export default new Vuex.Store({
  actions,
  mutations,
  state,
  getters
})

 

4.使用vuex(main.js)

import Vue from 'vue'
import App from './App.vue'
//引入store
import store from './store/moon'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  //使用store
  store
}).$mount('#app')

 

5.使用vuex操作数据

methods: {
      vuexs(){
        //使用actions
        this.$store.dispatch('setName','levi')
        //使用mutations
        this.$store.commit('SETNAME','levi')
        //使用getters
        let big=this.$store.getters.bigValue
        //使用state
        let name=this.$store.state.name
        let balance=this.$store.state.balance
      }
    }

 

posted on 2023-02-18 12:43  Mikasa-Ackerman  阅读(48)  评论(0编辑  收藏  举报

导航