Vuex状态管理

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。
vue组件通过dispatch方法触发Actions动作,然后Actions通过commit方法来触发Mutations,Mutations通过mutate方法来更改State状态,然后State状态再用render方法渲染到组件上。
Actions执行异步操作(比如后台调用API),Mutations执行同步操作。


Vuex生命周期

<h3>1. Vuex的安装</h3>
通过package.json将Vuex引入,通过 npm install安装。

<h3>2. Vuex的实例</h3>
<h5>2.1 项目引入Vuex</h5>
在main.js文件中引入Vuex,然后调用use方法使用,接着实例化一个store,将Vuex.Store传入store中,各种参数就在store中写。

import Vuex from 'vuex'
Vue.use(Vuex)
let store = new Vuex.Store({

})

<h5>2.2 Vuex的实现</h5>
demo实现效果:父组件中定义一个总数totalPrice,在子组件(page1)通过加减两个按钮,能对父组件的totalPrice实现增加,减少操作。(page1加减按钮一次操作数值为5)

在App.vue中
我们定义totalPrice 计算属性在页面显示,totalPrice的值通过Vuex下的store.getters中的getTotal计算出来。

<div>{{totalPrice}}</div>
 export default {
    computed: {
      totalPrice () {
        return this.$store.getters.getTotal
      }
    }

在page1子组件中
定义addOne和minusOne方法,用两个按钮承载。按下按钮会通过dispatch方法为increase,decrease这两个actions动作传入data中的price(即this.price)

<div>
    {{'名称:' + name}}
    {{'价格:' + price}}
    <button @click="addOne">加一</button>
    <button @click="minusOne">减一</button>
</div>
 export default{
    data () {
      return {
        name: '苹果',
        price: 5
      }
    },
    methods: {
      addOne () {
        this.$store.dispatch('increase', this.price)
      },
      minusOne () {
        this.$store.dispatch('decrease', this.price)
      }
    }
  }

在main.js中
①我们通过state来定义totalPrice这个变量。
②this.price传入actions中的increase和decrease后,actions 函数传入了context和price两个参数,price来接收this.price, 而context 对象与 store 实例具有相同方法和属性的,因此我们可以调用 context.commit 提交一个 mutation,把price提交过去。
③更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。我们也设置两个参数,第一个参数就是状态state,第二个参数就是price,我们通过price来接收commit过来的price,传入state是为了使用state.totalPrice这个回调函数,来对state下的totalPrice进行操作。
④我们在getters中定义getTotal这个方法,传入state,返回state.totalPrice,返回的值能被App.vue中的totalPrice直接调用。

let store = new Vuex.Store({
  state: {
    totalPrice: 0
  },
  getters: {
    getTotal (state) {
      return state.totalPrice
    }
  },
  mutations: {
    increment (state, price) {
      state.totalPrice += price
    },
    decrement (state, price) {
      state.totalPrice -= price
    }
  },
  actions: {
    increase (context, price) {
      context.commit('increment', price)
    },
    decrease (context, price) {
      context.commit('decrement', price)
    },
  }
})

把store放在这里,全局使用(跟vue-router一样)

const app = new Vue({
  el: '#app',
  store,
  render: h => h(App)
})
点击加一后
点击减一后

这样我们就完成了Vuex的整个生命周期。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容