Vuex的一些随笔
Vuex 和单纯的全局对象有以下两点不同:
-
Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
-
你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交(commit) mutations。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
-
const mutations = { // inc: state => state.count++,//这个和下面等价的,因为mutations里每个mutation都有一个回调函数,这个回调函数第一个参数就是state inc(state){ state.count++ } }
由于 Vuex 的状态存储是响应式的,从 store 实例中读取状态最简单的方法就是在计算属性(computed)中返回某个状态:
例子代码:
【main.js】
import Vue from 'vue' import App0 from './App0.vue' import store from './vuexs' new Vue({ store,//通过在根实例中注册store
选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过this.$store
访问到。 render: h => h(App0), }).$mount('#app')
【vuexs.js】
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const state = { // 这里放数据,相当于date count: 30 } const mutations = { // 这里放事件,比如点击后,要发生的事 inc: state => state.count++, dec: state => state.count-- } export default new Vuex.Store({ // 这里是注册,注册上面你写的方法 state, mutations })
【App0.vue】
<template> <div> 内容来自App0: <p>{{count1}} <button @click="inc">+</button> <button @click="dec">-</button> </p> </div> </template> <script> export default { computed: { count1 () { return this.$store.state.count } }, methods: { inc () { this.$store.commit('inc') }, dec () { this.$store.commit('dec') } }, } </script> <style> </style>