vuex概念
vuex 是一个状态管理工具,主要解决大中型复杂项目的 数据共享问题,主要包括
state,mutations,actions,getters 和 modules 5 个要 素,主要流程:在页面通过 调用dispatch触
发actions执行异步操作,在vue2中,不需要引入useStore,可以直接this.$store.dispatch,vue3最大的
特点是按需引入,用到那个api就要引入那个, actions里有默认参数context,在actions通过
context.commit(‘给mutations的事件’,‘给mutations的值’)调用mutations,在mutations中的默认参
数是state, mutations是唯一修改state的地方
1.特点(面试)
能够在vuex中集中管理共享的数据,易于开发和后期维护
能够高效地实现组件之间的数据共享, 提高开发效率
存储在 vuex中的数据都是响应式的,能够实时保持数据与页面的同步
一般情况下,只有组件之间共享的数据,才有必要存储到vuex中;
对于组件中的私有数据,依旧存储在组件自身的data中即可.
2.使用场景
如果你实在不知道开发中什么数据才应该保存到Vuex中,那你就先不用Vuex,需要的时候自然就会想到它
安装:
npm i vuex --save
导入:
import Vuex from "vuex"
Vue.use(Vuex)
创建仓库:
const store=new Vuex.Store({
state:{msg:"我就是所有共享的数据"}
})
把仓库挂载到vm对象:
new Vue({
render(h){return h(app)},
router,
store//挂载以后 所有的组件就可以直接从store中获取全局数据
}).$mount( "#app")
vue create app
选择配置vuex
我的建议:最好脚手架下载,反正我自己引入没引入成功,也可能代码有问题。
安装持久化插件
第一步安装 cnpm i vuex-persist --save
第二步 引入 本地存储持久化插件 import vuexPersist from "vuex-persist";
plugins: [ //第三步配置全局
new vuexPersist({
storage: window.localStorage,
}).plugin,
],
Vuex的基本结构
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: { //用于存放变量,类似于data
},
mutations: { //用于修改状态,类似于methods
},
getters: { //用于定义函数方法,类似于计算属性computed
},
actions: { //用于代替mutations执行异步操作
},
modules: { //类似于components
}
})
Vuex的基本使用
- 调用store(仓库)中的变量和方法
1、state状态
就是我们共享数据的存放位置,就与data书写形式一样,如:
var store=new Vuex.Store({
state: {
msg:"仓库中的数据",
arr:[{id:001,name:"zs"},{id:002,name:"ls"}],
obj:{a:1}
},
在组件中获取数据时,如获取msg为例,通过this.$store.state.msg。
这里的this.$store,是在引入时通过Vue.use(Vuex)时给Vue对象原型上绑定了的对象,所有组件中都可以使用
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
num: 0
},
mutations: {
add(state) {
state.num ++
},
sub(state) {
state.num --
}
},
getters: {
square(state) {
return state.num * state.num
}
}
})
- - - - - - - - - - - - - - - - - - - - - - - 分割线
<template>
<div id="app">
<h2>{{$store.state.num}}</h2> <!-- 调用state中的变量 -->
<h3>平方:{{$store.getters.square}}</h3> <!-- 调用getters中的square方法 -->
<button @click="sub">-</button>
<button @click="add">+</button>
</div>
</template>
<script>
export default {
name: 'app',
methods: {
add(n) {
this.$store.commit('add') //调用mutations中的add方法
},
sub() {
this.$store.commit('sub') //调用mutations中的sub方法
}
},
}
</script>
- vuex的getter方法也可返回一个函数和传递参数 它就好比我们学过的计算属性,每个方法内都会传入state,可以操作state内的数据。
例如:返回state中两个数的和
var store=new Vuex.Store({
state: {
a:1,
b:2
},
getters:{
sum(state){
return state.a+state.b
}
}
})
获取sum:this.$store.getters.sum
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
students: [
{id: 101, name: '张三'},
{id: 102, name: '李四'},
{id: 103, name: '王五'},
{id: 104, name: '赵六'},
]
},
getters: {
getid(state) {
return function(id) {
return state.students.filter(s => s.id == id)
}
}
}
})
- - - - - - - - - - - - - - - - - - - - - - - 分割线
<template>
<div id="app">
<h2>获取学号是102的学生信息:{{$store.getters.getid(102)}}</h2>
</div>
</template>
- vuex的mutations方法携带参数 这个配置用于修改state中的数据,官方文档中它是在同步代码中实现,但是我们自己测试的时候在里面写异步代码也能实现。
还有,官方文档中说它是更改 Vuex 的 store 中的状态(数据)的唯一方法,不要用赋值表达式直接在组件中给store设置新数据,但是直接赋值效果也能够实现。
组件中修改state的数据,需要用到$store一个方法commit(),它的作用是传递参数并触发mutaition里对应的方法(专业说法为提交负荷)。
commit()的传参
1、普通形式:commit("name",d),这里的name为mutaitions中配置的方法名,d为我们传递的参数,可以是数字、数组、对象等。
2、以对象形式传入:commit({type:"name",d:dd}),把整个对象作为了第二个参数传入mutations,type对应的就是mutaitions中配置的方法名。
mutaitions里面的配置:
mutations: {
name(state,arg){
//业务
},
name为方法名,第一个参数是传入的state,第二个参数就是commit传来的参数。
完整实现一下:在box组件中修改state中的值
box.vue:
mounted(){
this.$store.commit("change",11)
}
store下的index.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)//让组件的原型链中 有仓库的工具代码
export default new Vuex.Store({
state: {
num:1
},
mutations: {
change(state,arg){
state.num=arg
}
},
})
程序一运行,state中的num由1就变成了11.
<template>
<div id="app">
<h2>{{$store.state.num}}</h2>
<button @click="sub(2)">-2</button>
<button @click="add(5)">+5</button>
</div>
</template>
<script>
export default {
name: 'app',
methods: {
add(x) {
this.$store.commit({ //这种方式可传递多个变量,多个变量会作为一个对象被接收
type: 'add',
x,
//...
})
},
sub(x) {
this.$store.commit('sub', x) //这种方式只可传递一个变量
}
},
}
</script>
- - - - - - - - - - - - - - - - - - - - - - - 分割线
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
num: 0
},
mutations: {
add(state, n) { //这里的n是一个对象
state.num += n.x
},
sub(state, n) { //这里的n是一个变量
state.num -= n
}
}
})
- 4、Action
Action 可以包含任意异步操作,它的作用就像一个中转站,当修改的state的代码不是异步的或者是没有什么逻辑判断,我们直接在组件中commit操作Mutaitions;但是当存在异步操作或者很多逻辑判断时,我们一般就要加上Action这一步,组件中先将数据传递给Action,Action处理后再传给Mutaitions。
组件中传递信息给Action需要用到$store上的dispacth方法,它的传参跟commit传参形式是一样的,一种是普通形式,一种是对象形式。
actions中的配置是方法传来的两个参数,第一个不再是state,而是一个上下文对象,是一个简化了的store对象;第二个参数为组件中传递的数据。
流程非常简单,就是:组件——>Action——>Mutaition
代码展示:
组件中:
mounted(){
this.$store.dispatch("change",11)
}
actions和mutaitions中:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)//让组件的原型链中 有仓库的工具代码
export default new Vuex.Store({
state: {
num:1
},
actions:{
change(context,arg1){
//异步处理
setTimeout(()=>{
context.commit("change1",arg1)
})
}
},
mutations: {
change1(state,arg2){
state.num=arg2
}
},
})
- 5、Module
可用于业务分块开发: 由于使用单一状态树,应用的所有状态(数据)会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。 为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter
具体使用:
分块做业务时,一个对应一个store这样不容易混乱,而且模块化开发更容易维护。
一个人对应一个js文件,在里面配置自己的 state、mutation、action、getter,然后导入导出到index.js文件中,放到modules配置项中。
如:自己的js文件
export default {
namespaced: true,//局部命名空间(让state的中变量与其他模块中的同名变量不冲突)
state: {
msg:"张三的公共数据"
},
getters: {
...
},
mutations: {
....
},
actions: {
...
}
}
index.js中引入:
import Vue from 'vue'
import Vuex from 'vuex'
import Model1 from "./Model1.js"
Vue.use(Vuex) //让组件的原型链中 有仓库的工具代码
export default new Vuex.Store({
state: {
},
getters: {
},
mutations: {
},
actions: {
},
modules: {
Model1,
}
})
使用时,某个组件要使用Model1中的公共数据:this.$store.state.Model1.msg;
要使用Model1中motaitions配置的方法:this.$store.commit("Model1/change",num);
使用getters:this.$store.getters["Model1/x"];
使用dispatch:this.$store.dispatch("Model1/change",num)
页面调用actions的方法:
created() {
this.$store.dispatch("methodName");//调用vuex的异步请求actions
},
总体拉伸一遍
/**
* store/index.js
*
*/
import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
Vue.use(Vuex);
//vuex下的持久化插件 用在vuex里的插件 !!!所以只能在vuex/store/index 引入
import vuexPersist from "vuex-persist"; //第二步 引入 本地存储持久化插件 第一步安装cnpm i vuex-persist --save
export default new Vuex.Store({ //Store仓库的意思
state: { //存数据 状态的意思 status也是状态的意思
list: [],
},
mutations: { //相当于methods 只有mutations才可以修改该state 转变的意思 commit//委托的意思 第一参数state
changeData(state, val) {
// state.list = val
//不直接将参数赋值,如果本地存储有或空,就将本地的赋值给list,否则直接将参数赋值给list
if (JSON.parse(localStorage.getItem('list')) || []) {
state.list = JSON.parse(localStorage.getItem('list')) || []
} else {
state.list = val
}
//以上代码目的打开页面如果本地有数据,就使用本地的,不会一打开就重新将data.JSON的值赋值给list
console.log(state.list);
},
},
actions: { //动作的意思 执行异步操作的 dispatch//派遣的意思 actions第一个参数永远是context
methodName(context) {
axios.get('/data.json').then(res => {
// console.log(res.data.data);
context.commit('changeData', res.data.data)
//页面触发action,action触发mutation,从而修改state中的数据,因为mutation不能写异步代码
})
}
},
modules: { //加载模块的意思 当数据state较多的时候可以分模块管理
},
getters: { //相当于计算属性 获取的人的意思
//在页面使用 {{$store.getters.obj.num0}}
// obj(state) {
// let num0 = state.list.filter(v => v.status == 0).length
// let num1 = state.list.filter(v => v.status == 1).length
// let num2 = state.list.filter(v => v.status == 2).length
// return { num0, num1, num2 }
// }
},
plugins: [ //第三步配置全局
new vuexPersist({
storage: window.localStorage,
}).plugin,
],
});
建议在computed:{ }中使用,如果在data中使用,修改了vuex的数据data不会改变重新渲染,使用computed当依赖值发生改变就会重新渲染
在页面取vuex的数据如下(不使用辅助函数)
* views/home.vue
*/
<template>
<div class="home">
<div>{{ changeText }}</div> //666 ! 成功修改了state的666变成666 !
</div>
</template>
<script>
export default {
data() {
return {
};
},
computed: {
changeText() {
return (this.$store.state.test = "666 !");
},
},
};
</script>
/**
* store/index.js
*/
export default new Vuex.Store({ //Store仓库的意思
state: { //存数据
test: '666'
},
)}
高阶辅助函数,需引入
为什么用辅助函数
- 引入辅助函数可以简写不写this.$store.state
需要注意的是mapState和mapGetter是映射为计算属性,获取数据
而mapMutations 和mapActions是映射为methods方法里,修改数据的
1.1 有4个辅助函数(4大映射) mapState,mapActions,mapMutations,mapGetters 1.2 辅助函数可以把vuex中的数据和方法映射到vue组件中。达到简化操作的目的
mapState 是vuex的一个辅助函数 他可以通过循环vuex中的state中的数据将数据一一取出 方法需要在computed计算属性中使用 使用数组 computed:{...mapStore([‘xx’]}
其他三个同理推出...
使用对象可以重命名vuex的数据名字computed:{{自定义名称:xxx数据}}
用辅助函数调用vuex中的方法
/**
* views.home.vue
* 调用vuex中的方法
*/
<template>
<div class="home">
<button @click="btn">按钮</button>
</div>
</template>
<script>
import { mapMutations } from "vuex";
export default {
data() {
return {};
},
methods: {
...mapMutations(["addAge"]),//相当于data中的数据可直接用this调用
btn() {
this.addAge();
},
},
};
</script>
<style lang="scss" scoped></style>
/**
* store/index.js
*/
mutations: {
addAge(state) {
alert('789456123')
}
},
用辅助函数 调用vuex中的数据
/**
* views.home.vue
* 调用vuex中的数据
*/
//1 引入
import { mapState } from 'vuex'
//2 在compued使用
computed: {
...mapState(['goods']) // [‘goods’]是数据加中括号[] 可以映射vuex数据到当前页面直接使用vuex/state中的goods数据,不需要$store.state.goods
},
//vuex
state: { //存数据
goods: '666'
},