detools插件作用:跟踪记录每一次改变state的状态,从而知道是哪个组件修改了state (前提:state是通过mutations修改)
如下例,目标为通过点击按钮修改mutations中的counter
vuex配置文件index.js
创建store文件夹,在其中创建index.js文件来存放Vuex配置代码
import Vue from 'vue'
import Vuex from 'vuex'
//1、安装插件
Vue.use(Vuex)
//2、创建对象
const store = new Vuex.Store({
state:{
counter:0
}, //state中存放数据
mutations:{
increament(state){
state.counter++
} //mutations中确定方法
}
})
//导出store
export default store
挂载到Vue实例中
为了让所有的Vue组件都可以使用这个store对象:
在main.js中导入store对象,并且放在new Vue中,这样,在其他Vue组件中,就可以通过this.$store的方式,获取到这个store对象
main.js文件:
import Vue from 'vue'
import App from './App'
import store from './store'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
render: h => h(App)
})
在其他组件中使用store对象
组件App.vue:
<template>
<div id="app">
<h2>{{message}}</h2>
<h2>{{$store.state.counter}}</h2>
<button @click="addition">按钮</button>
<hello-vuex :counter="$store.state.counter"></hello-vuex>
</div>
</template>
<script>
import HelloVuex from './components/HelloVuex'
export default {
name: 'App',
components: {
HelloVuex
},
data(){
return {
message:'你好啊',
}
},
methods:{
addition(){
this.$store.commit('increament') //提交
}
}
}
</script>
<style>
</style>
注:在其他组件中使用store对象时,不能直接引用mutations中的方法,需在当前组件的methods中,通过this.$store.commit(‘store对象中方法’) 的方式
效果:
点击按钮后,成功通过mutations修改counter,并且能够在devtools进行实时跟踪,需要时,还能对每一步进行调试