Vuex是一个专为Vue.js应用程序开发的状态管理模式,为多个组件共享状态的插件
状态–>变量
需要共享的状态才需放入Vuex中
npm i xxx --save-dev 是把依赖写入进devDependencies对象里面
npm i xxx --save 是把依赖写入进dependencies对象里面
npm i xxx -g 就是安装到全局下,在命令行的任何地方都可以操作,不会提示“命令不存在等错误”
安装vuex插件
npm install vuex --save
如果要修改state状态,不能用组件直接修改,要通过mutations修改,便于devtools记录修改历史,跟踪修改记录。
Vuex的使用流程
1.下载Vuex插件:
npm install vuex --save
2.在src文件夹中创建store文件夹,然后在其中创建index.js文件:
import Vue from 'vue'
import Vuex from 'vuex'
//1.安装插件
Vue.use(Vuex)
//2.创建对象
const store = new Vuex.Store({
state: {
counter: 10
},
mutations: {
//方法
increment(state) {
state.counter++
},
decrement(state) {
state.counter--
}
}
})
//导出
export default store
3.在main.js文件中引用:
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store/index'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
4.最后在App.vue文件中使用:
<template>
<div id="app">
<h2>{{message}}</h2>
<h2>{{$store.state.counter}}</h2>
<button @click="add">+</button>
<button @click="sub">-</button>
<hello-world></hello-world>
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld";
export default {
name: "App",
components: {
HelloWorld,
},
methods: {
add() {
this.$store.commit("increment");
},
sub() {
this.$store.commit("decrement");
},
},
data() {
return {
message: "我是app组件",
counter: 0,
};
},
};
</script>
<style>
</style>
Vuex核心概念
- state-状态属性-变量-数据
- getters:
类似于计算属性,处理state里的数据
使用getters传入参数:
使返回值为一个函数
passNum(state) {
return function (num) {
return num * num
}
}
这样就可以在调用中传参:
<h2>{{$store.getters.passNum($store.state.counter)}}</h2>
- mutation
Vuex的store状态更新的唯一方式:提交Mutation
在更新数据时传递参数:
参数被称为是mutation的载荷(payLoad)
mutations: {
//方法
increment(state, n) {
state.counter += n
},
decrement(state, n) {
state.counter -= n
}
}
add() {
this.$store.commit("increment", 100);
},
sub() {
this.$store.commit("decrement", 0.1);
},
如果传递的不是一个参数,payload可以是个对象
//方法
increment(state, payload) {
state.counter += payload.n
console.log(payload);
},
add() {
this.$store.commit("increment", { n: 111, m: 222 });
},
mutation的响应规则
vuex的store中的state是响应式的,当state中的数据发生改变时,Vue组件会自动刷新
前提:
- 提前在store中初始化好的属性
- 当给state中的对象添加新属性时,使用下面的方式:
方式一:使用Vue.set(obj,‘newProp’,123) (删除对象用Vue.delete())
方式二:用新对象给旧对象重新赋值
action - 替代mutation完成异步操作
- aciton提交的是mutation,而不是直接变更状态
- action可以包含任意异步操作
module
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割: