您的位置:首页 > Web前端 > Vue.js

Vuex基本概念和操作过程

2020-08-18 07:26 127 查看

Vuex

1.Vuex是什么

Vuex是一个vue的插件,是一个基于vue.js开发的状态管理工具(模式),说白了就是多个组件用来存放、修改、处理的一个容器(仓库),就是用来存放处理公共数据的工具,数据变了组件就会更新,也就是说存放的数据是响应式的。

什么是状态管理模式?
简单的Vue计数案例:
new Vue({
//state
data(){
return {
const:0
}
}
})
//view
template:`
<div>{{ const }}</div>
`,
//actions
methods:{
increment () {
this.count++
}
}

这个状态自管理应用包含以下几个部分:
1.state,驱动应用的数据源
1.view,以声明方式将 state 映射到视图
3.actions,响应在 view 上的用户输入导致的状态变化

如何获取Vuex中state的数据
通过this.$store.state.仓库中的数据

如何获取到仓库中定义的方法
通过this.$store.state.commit("mutations中定义改变state的事件")

核心概念

1.state(Vuex数据源)
在组件中通过computed计算属性的写法来获取Vuex中state的数据来实现当每次state中的值发生变化的时候都会重新求取计算属性,并触发相关DOM
<template>
<div>
{{ count }}
</div>
</template>

<script>
export default {
computed:{
count(){
rerurn $store.state.count
}
}
}
</script>

辅助函数:mapState
在组件中引入mapState
import { mapState } from 'vuex'

组件内渲染就好
// 第一种映射方式
computed:mapState(['msg','age','sex','num']),
methods:{
changeValue(e){
this.$store.commit('addNum',e.target.value)
}
}

//第二种映射方式
data:()=>{
return{
color:"red"
}
},
computed:mapState({
msg:'msg',
age:(state)=>state.age,
Msg:function(state){
return this.color+state.sex
}
})

// 第三种映射方式
computed:{
...mapState({
msg:'msg',
age:(state)=>state.age,
Msg:function(state){
return this.color+state.sex
}
})
}
简写:computed:mapState([//state里面的key])

2.Getter
其实就像当与computed和filter一样,对state中的数据进行一些过滤计数的操作
Vuex中:
getters:{
reverseMsg(state){
return state.msg.split('').reverse().join('')
},
b(state){
return (val)=>{
return val+state.msg
}
}
使用辅助函数:在组件中引入mapGetters
import { mapGetters } from 'vuex'

computed:{
b:function(){
return this.$store.getters.b('7899')
},
...mapGetters(['reverseMsg'])
}

3.Mutation
可以在Mutation中对state中的数据进行一些改变的方法,也是Vuex中对事件和方法操作的地方
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
}
不同辅助函数可以通过this.$store.state.commit("mutations中定义改变state的事件")

辅助函数:mapMutations
import { mapMutations } from 'vuex'
在methods中使用

4.Action(是Vuex中对异步操作和请求数据的一些处理)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
不用辅助函数在组件内通过$store.state.dispatch("Action中定义的方法名")

辅助函数用法:mapActions
import { mapActions } from 'vuex'
在methods中使用

5.Module
Module是当一个比较大型的应用时,state的对象可能就变得臃肿,为了解决这个问题Vuex允许我们将stote分割成模块(module),每个模块可以拥有自己的state,getter,mutation,Action、还可以做到嵌套,使得方便管理
const moduleA = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}

const moduleB = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... }
}

const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态

命名空间:namespaced: true  / 形式:foo/someOtherGetter
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: