五分钟搞懂Vuex实用知识(小结)

2020-06-13 10:40:16易采站长站整理


import Vue from 'vue'
import App from './App'
import router from './router'
import store from './vuex/store' // 引入store
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})

然我我们在任意一个组件中就可以使用我们定义的count属性了。

这里我们在helloWorld中使用一下,去除helloworld.vue中不用的标签


<template>
<div class="hello">
<h3>{{$store.state.count}}</h3>
</div>
</template>

打开我们刚才运行项目的浏览器,可以看到已经使用成功了!

并且在vue开发工具中我们可以看到我们定义的变量count

到这一步,已经成功了一小半!vuex很简单吧?

回想一下,我们只需要在下载安装使用vuex,在我们定义的store.js中定义state对象,并且暴露出去。

在main.js中使用我们的store.js(这里是为了防止在各个组件中引用,因为main.js中,有我们的new Vue 实例啊!)

现在我们已经使用了vuex中的state,接下来我们如何操作这个值呢? 没错!用mutations和actions

我们继续操作store.js文件

我们在sotre.js中定义mutations对象,该对象中有两个方法,mutations里面的参数,第一个默认为state,接下来的为自定义参数。

我们在mutations中定义两个方法,增加和减少,并且设置一个参数n,默认值为0,然后在Vuex.Store中使用它


/**
* mutations 里面放置的是我们操作state对象属性的方法
*/
const mutations = {
mutationsAddCount(state, n = 0) {
return (state.count += n)
},
mutationsReduceCount(state, n = 0) {
return (state.count -= n)
}
}
export default new Vuex.Store({
state,
mutations
})

然后我们在helloWorld.vue中,使用这个方法

还记得我们如何在组件中使用mutations吗?就和自定义事件非常相似


<template>
<div class="hello">
<h3>{{$store.state.count}}</h3>
<div>
<button @click="handleAddClick(10)">增加</button>
<button @click="handleReduceClick(10)">减少</button>
</div>
</div>
</template>


methods: {
handleAddClick(n){
this.$store.commit('mutationsAddCount',n);
},
handleReduceClick(n){
this.$store.commit('mutationsReduceCount',n);