1.介绍
VueX是适用于在Vue项目开发时使用的状态管理工具。试想一下,如果在一个项目开发中频繁的使用组件传参的方式来同步data中的值,一旦项目变得很庞大,管理和维护这些值将是相当棘手的工作。为此,Vue为这些被多个组件频繁使用的值提供了一个统一管理的工具——VueX。在具有VueX的Vue项目中,我们只需要把这些值定义在VueX中,即可在整个Vue项目的组件中使用。
2.安装
npm i vuex -s
3.使用
注:在Vue3中已经自动配置好Vuex,无需手动配置,如果你使用的vue2,那么以下是配置方式:
(1) 在项目的根目录下新增一个store
文件夹,在该文件夹内创建index.js
此时你的项目的src
文件夹应当是这样的:
│ App.vue
│ main.js
│
├─assets
│ logo.png
│
├─components
│ HelloWorld.vue
│
├─router
│ index.js
│
└─store
index.js
(2) 初始化store
下index.js
中的内容
import Vue from 'vue'
import Vuex from 'vuex'
//挂载Vuex
Vue.use(Vuex)
//创建VueX对象
const store = new Vuex.Store({
state:{
//存放的键值对就是所要管理的状态
name:'helloVueX'
}
})
export default store
(3) 将store挂载到当前项目的Vue实例当中去
打开main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store, //store:store 和router一样,将我们创建的Vuex实例挂载到这个vue实例中
render: h => h(App)
})
(4) 在组件中使用Vuex
例如在App.vue中,我们要将state中定义的name拿来在h1标签中显示
<template>
<div id='app'>
name:
<h1>{
{ $store.state.name }}</h1>
</div>
</template>
或者要在组件方法中使用
...,
methods:{
add(){
console.log(this.$store.state.name)
}
},
...
注意,请不要在此处更改state中的状态的值
4.Vuex和EventBus的区别
vuex 的底层实现原理其实就是 event-bus,那么它和普通的 event-bus 有什么不同呢?我们通过简单的源码一步步实现来搞懂这个问题。
- EventBus
首先一个普通的 event-bus 是这样的:
// main.js
Vue.prototype.$bus = new Vue();
// 组件中
this.$bus.$on('console', (text) => {
console.log(text);
});
// 组件中
this.$bus.$emit('console', 'hello world');
它是通过 Vue 的$on
和$emit
api 来传递消息的。
- vuex 的响应式数据
而 vuex 的数据是响应式的,那么我们首先实现这种响应式数据:
class store {
constructor(options) {
this.vm = new Vue({
data: {
state: options.state
},
});
}
get state() {
return this.vm.state;
}
}
注意,上面的data不是一个函数,因为这里我们只会实例化一次。然后我们通过添加一个 state 的 getter 方法来暴露内部的 event-bus 的 state 属性。
那怎么实现响应式的呢?因为在实例化 vm 的时候,Vue 会自己使用 defineReactive 把 data 变为响应式数据,从而会收集有关它的依赖,然后在自己变动的时候,通知依赖更新。
- 加上 getters
vuex支持加上 getters,怎么加呢?直接初始化一个 getters 属性即可:
class store {
constructor(options) {
this.vm = new Vue({
data: {
state: options.state
},
});
const getters = op