一、什么是Vuex?
Vuex是一个专为vue.js应用程序开发的状态管理模式。
当我们构建一个中大型的项目时,Vuex可以更好的帮助我们在组件外部统一管理状态。
安装
以下步骤的前提是你已经完成了Vue项目构建,并且已转至该项目的文件目录下。
1.npm/cnpm安装Vuex
npm install vuex
2.在项目的根目录下新增一个store文件夹,在该文件夹内创建index.js , 初始化store下index.js中的内容 代码如下
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
//导出创建好的Vuex构造器
export default new Vuex.Store({
state:{
//存放的键值对就是所要管理的状态
name:'helloVueX'
}
})
3.将store挂载到当前项目的Vue实例当中去
在mian.js中引入
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'
import store from './store/index'//引入store下的index.js
Vue.config.productionTip = false
Vue.prototype.axios=axios;
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
4.在组件中使用Vuex
在组件标签中显示
<h1>{{this.$store.state.name}}</h1> //==>helloVueX
二、VueX中的核心内容
vuex中的核心属性,详细解读
state => 基本数据
getters => 从基本数据派生的数据
mutations => 提交更改数据的方法,同步!
actions => 像一个装饰器,包裹mutations,使之可以异步。
modules => 模块化Vuex
plugins => 插件
1.state
state是存储的单一状态,是存储的基本数据。
export default new Vuex.Store({
state:{//声明数据
shopCar:[],
n:0,
user:{}
msg:'',
age:20,
name:'www',
},
})
2.getters
getters中的方法有两个默认参数
1.state 当前VueX对象中的状态对象
2.getters 当前getters对象,用于将getters下的其他getter拿来用
如不需要,第二个参数可以省略如下例子:
getters:{
getsum(state){//相当于state的计算属性
var sum=0
for(var i = 0;i<state.shopCar.length;i++){
sum+=state.shopCar[i]
}
return sum
},
//两个默认参数
nameInfo(state){
return "姓名:"+state.name
},
fullInfo(state,getters){
return getters.nameInfo+'年龄:'+state.age
}
}
组件中调用
<h3>购物车{{$store.getters.getsum}}</h3>
console.log(this.$store.getters.fullInfo); // 姓名:www年龄:20
3.mutations
提交mutation是更改Vuex中的store中的状态的唯一方法。
mutation必须是同步的,如果要异步需要使用action
每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数,提交数据作为第二个参数。(如果没有传输数据,第二个参数也可省略) 例子如下
mutations:{//修改数据
increment(){ //变更状态
this.state.n++
},
jianjian(state){
state.n--
}
addUserName(state,val){
state.shopCar.push(val)
},
}
在组件中调用
//1.不含数据
jian(){
this.$store.commit('jianjian')
},
//2.传输数据
tj(item){
this.$store.commit('addUserName',item)
},
4.actions
action 类似于 mutation,不同在于:
action 提交的是 mutation,而不是直接变更状态。
action 可以包含任意异步操作。
actions中的方法有两个默认参数
state
val 挂载参数
我们用如下例子来讲述actions:
actions:{
uperKey(state,val){
setTimeout(() => {
state.commit('uperKey',val)
}, 10);
}
}
mutations:{//在mutation里处理修改数据
uperKey(state,val){
state.msg = val
}
},
在组件中调用
this.$store.dispatch('uperKey',10)
5.Modules 模块化vuex
当项目变得很大时,store 对象会变得臃肿不堪。
为了解决以上问题,Vuex 允许我们将 store 分割到模块(module)。每个模块拥有自己的 state、mutation、action、getters、使得结构非常清晰,方便管理——从上至下进行类似的分割:
import user from './user.js'//先引入单个模块文件
modules:{
user,
},
user.js 结构内容
export default {
state:{
user:{},
},
mutations:{
user(state,item){
state.user=item
}
},
getters:{},
action:{},
}
组件调用时需要加上模块名
this.$store.state.user.user.id
6.plugins 插件
先看一个简单地插件,长久储存
下载插件
npm/cnpm install vuex-localstorage
引入
import createPersist from 'vuex-localstorage'
plugins:[//pligins插件
createPersist({namespace:'namespace-for-state'})
],