vue状态管理
入门
一、首先,初始化vue工程
vue init webpack vue01
最后一项可以选择no,然后使用cnpm进行安装,防止卡死。
二、安装vuex
cnpm install --save vuex
三、在src目录下创建store目录,并创建index.js文件
//定义vuex的store对象
//1.显示调用vuex
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
//2.创建状态管理对象
let store = new Vuex.Store({
state:{
//定义共享变量
count:0
}
})
//3.导出对象
export default store
四、在main.js中启用store
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
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',
store,
router,
components: { App },
template: '<App/>'
})
五、页面中显示共享数据
$store
内置对象(容器)
state
(状态管理对象)
{{$store.state.count}}
mutation改变状态值
在store容器中,定义mutation,其中定义改变状态值的方法。
//2.创建状态管理对象
let store = new Vuex.Store({
state:{
//定义共享变量
count:0
},
mutations:{
increament:function(state,step){
state.count+=step
}
}
})
页面中调用改变状态值的方法
this.$store.commit("方法名",参数值)
methods:{
test:function(){
//不能直接改变共享变量,不能直接调用multation的方法
this.$store.commit("increament",2)
}
}
也可以使用actions,来间接调用mutations
//2.创建状态管理对象
let store = new Vuex.Store({
state:{
//定义共享变量
count:0
},
mutations:{
increament:function(state,step){
state.count+=step
}
},
//间接调用mutations
actions:{
increamentAction:function(context){
context.commit("increament",1)
}
}
})
methods:{
test:function(){
//不能直接改变共享变量,不能直接调用multation的方法
//this.$store.commit("increament",2)
this.$store.dispatch("increamentAction")
}
}
派生属性getters
定义派生属性level,让它随着count的值而变化
//2.创建状态管理对象
let store = new Vuex.Store({
state:{
//定义共享变量
count:0
},
mutations:{
increament:function(state,step){
state.count+=step
}
},
//间接调用mutations
actions:{
increamentAction:function(context){
context.commit("increament",1)
}
},
//派生属性 getters
getters:{
level:function(state){
if(state.count < 5){
return "低级"
} else if (state.count >= 5){
return "中级"
}
}
}
})
级别:{{$store.getters.level}}
模块化
基本目录结构:
- 让共享属性写在modules目录的不同js文件中
- 让派生属性写在getters.js中
- 吧拼接的任务交给index.js
一、创建目录
二、创建共享属性module1
export default{
state:{
//定义共享变量
count:0
},
mutations:{
increament:function(state,step){
state.count+=step
}
},
//间接调用mutations
actions:{
increamentAction:function(context){
context.commit("increament",1)
}
},
}
三、创建派生属性level
export default{
//派生属性 getters
level:function(state){
if(state.a.count < 5){
return "低级"
} else if (state.a.count >= 5){
return "中级"
}
}
}
四、拼接共享属性和派生属性
//1.显示调用vuex
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
import module1 from "./modules/module1"
import getters from "./getters"
let store = new Vuex.Store({
getters,
modules:{
a:module1
}
})
export default store