Vuex-用户需求与数据处理
1.Vuex的五要素:
Vuex通过实例化成对象Store,随后挂载成全局对象,它一共有五个属性:
state 用于存放数据,类似于组件中的data
不同之处:state所存放的数据是公用的,但是组建中的data是私有的,所以在整个项目的随意一个组件中都可以调取和修改Store中的数据
所以才会存在父子组件、兄弟组件之间的通信(传值),后续给大家一一讲解父子组件、兄弟组件之间的通信方式
Mutations:存放改变state中存放的数据的方法。只能处理同步请求
Actions:调取Mutations中的方法,而Actions由用户的需求来触发,它可以处理异步请求。
getters:进行过滤或计算。类似于组件中的computed和filter的结合体
module:管理多个Vuex实体(store)
2.具体流程:
用户提出需求(事件触发)->触发actions,actions通过commit(‘mutations中定义的方法名’,传递的参数(选))->mutations对state中的数据进行修改
3.具体实例
1.在vue创建的项目下创建一个文件为store/index.js
import Vue from 'vue'
// 引入vuex
import Vuex, { Store } from 'vuex'
// 注册
Vue.use(Vuex)
// 实例化Store对象并导出
export default new Store({
state: {
count: 1
},
mutations: {
sup (state) {
this.state.count++
}
},
actions: { // 可以执行异步的操作
async Sup ({ commit }, obj) {
commit('sup', obj)
}
}
})
2.初始化store后,将store挂载到main.js中(main.js是一个项目的入口文件)
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
3.这些准备工作都做好了接下来就是在组件中随表找个地方来触发改变state数据的函数,这里我们找到的是home/index.vue
在App.vue中挂载store里面的count:,在home/index.vue也定义一个count
// App.vue
<template>
<div id="app">
<div id="nav">
Store 中的count {{$store.state.count}}
</div>
<router-view/>
</div>
</template>
// Home/index.vue
<template>
<div class="home">
home组件调取Store的count --> {{$store.state.count}}
<button @click = "sup">Store++</button>
</div>
</template>
效果如下:
点击按钮: