一、state
1、保存数据
仓库中保存数据:
export default new Vuex.Store({state: {num: 0}})
2、访问数据
组件中获取数据:
<template><div><h1>直接从仓库获取: {{ $store.state.num }}</h1><h1>通过 computed 获取: {{ computedNum }}</h1></div></template><script>export default {computed: {computedNum() {return this.$store.state.num;}}}</script>
我们可以直接获取仓库数据并使用,也可以用计算属性获取仓库数据,然后使用计算属性。
二、mutations
1、设置方法
设置仓库中的 mutations 方法:
export default new Vuex.Store({state: {num: 1},getters: {},mutations: {INCREMENT(state) {state.num++;},DECREMENT(state) {state.num--;}}})
说明:mutations 中的方法名并不一定非要用纯大写,可根据自己的习惯来。
2、调用方法
组件中调用仓库 mutations 的方法:
<template><div><h1>直接从仓库获取: {{ $store.state.num }}</h1><h1>通过 computed 获取: {{ computedNum }}</h1><button @click="$store.commit('DECREMENT')">-1</button><button @click="increment">+1</button></div></template><script>export default {computed: {computedNum() {return this.$store.state.num;}},methods: {increment() {this.$store.commit('INCREMENT');}}}</script>
