首先在App.vue中定义counter
<h2>{{counter}}</h2>
<button @click="counter++">+</button>
<button @click="counter--">-</button>
data() {
return {
counter: 0
};
}
再创建一个TextVuex.vue文件,想要获取到App.vue文件中的counter(忽略它们之间的父子组件关系),并且当点击+和-时,两个vue文件中的counter同步变化,即做到响应式。
将counter变量放到vuex(vue状态管理模式)中
npm install vuex --save 安装vuex
在src文件下创建store文件,在store文件下创建index.js文件
index.js文件中的基础配置
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {},
mutations: {},
actions: {},
modules: {}
})
将counter放在state中
state: {
counter: 0
},
在main.js中注册
import store from './store'
new Vue({
store
})
在App.vue和TextVuex.vue文件中使用
<h2>{{$store.state.counter}}</h2>
如果想要点击+和-改变counter的值,最简单的方法是
<button @click="$store.state.counter++">+</button>
<button @click="$store.state.counter--">-</button>
这样可以运行,但是是不对的。
官网推荐,可以通过state修改vue component中的值,但是不能直接通过vue组件修改state中的值,因为直接修改的话,不能被Devtools所监控到。
devtools插件作用:跟踪记录每一次改变state的状态,从而知道是哪个组件修改了state
如果想要通过vue组件修改state中的值,有两个途径。
途径一:
当没有出现异步操作时,跳过Actions是可以的。
Actions的作用是让mutations中的方法能在异步操作中起作用。Actions连接的Backend API是后端API.
途径二:
先通过Actions处理出现的异步操作,再通过Mutations监控。
修改state方法
在mutations中
mutations: {
increment(state) {
state.counter++;
},
decrement(state) {
state.counter--;
}
},
在App.vue文件中通过commit提交
methods: {
add() {
this.$store.commit("increment");
},
sub() {
this.$store.commit("decrement");
}
}
调用方法
<button @click="add">+</button>
<button @click="sub">-</button>