1.(面试必问 大项目)单向数据流导致可能层级较深(管理全局的状态)
- state:数据源
- view :将state数据到视图
- actions:状态变化
2.小项目用麻烦
mutations:修改数据的对象(不可以异步)
3.组成
-
state:
-
getters:得到数据
-
mutations:
-
actions:
-
mapState:得到State
-
mapActions:
-
mapMuta:
4.安装
yarn add vuex@next --save
5.使用
建一个js文件
import{createStore} from 'vuex'
const store=createStore({
//strict:true//使用严格模式,一般生产环境不用会造成性能损失
strict:process.env.NODE_DEV!='production',
//在拿到node的环境配置判断是否是生产环 境,不是生产环境为true
//不是由mutation执行的函数,会破坏vuex的使用流程
//全局的数据
state:{
counter:10
},
getters:{//相当于计算属性,就是来处理state的
},
//提交操作给mutation(可同步或者异步)
actions:{//提交的方法,提交才能执行mutation的方法
increment({commit},num){
commit('INCREMENT',num);
},decrement({commit}){
}
}
,
//同步提交状态,结构 改变
mutations:{//写修改的方法,只能是同步的方法
INCREMENT(state,num){
state.count++;
},
DECRAMENT(state){
state.count--;
}
}
});
export default store
main.js中创建vue对象中使用
import store from '..../index.js'
app.use(store)
App.vue 页面直接写(不用引入)
{{$store.state.counter}}//
6.修改state状态
import {useStrore} from 'vuex'
setup(){
const store=useStore();
//直接修改,不可取
//store.state.counter=1;
const add=()=>{
//派发任务,devTools可以追踪状态
store.dispatch('increment');
//store.commit("INCREMENT",num) 直接在mutation操作数据并且传入一个num
}
return{add}
}
7.异步状态
strict选项//如上代码
action:可以是异步的如网络请求
8.简化代码(返回的值用计算属性包裹)
setup(){
....
return {
count:computed(()=>store.state.count),
add:(num)=> store.commit('INCREMENT',num),
sub:(num)=> store.dispatch('decrement',num)
}
}
9.分离里面的选项各自为js文件
export default{
count:10
}
10.解决字符串名不提示的问题用es6语法
导入导出常量
export default
11.传入对象
store.commit("INCREMENT",{obj})
12.mutations.js的es6写法(代表里面可以使用这个东西)
//可以有提示
[DEL_TODO](state,{index}){
}
13.{commit}是什么,其实是vuex对象里面的对象的方法(有的像es6解构)
//可以写为其他方式
addToDo(context,index){
//之前的写法 context.commit(DEL,{index})
context.commit(DEL,{index})
//{index:index}的简写
}
14.vuex响应式系统(数据可以动态变化,如果数据源改变,全部使用这个数据的都会改变)
在mutations中改变数据 追加 删除数据
state.college.name='xxx'
//追加,加一个不存在的名字可追加
state.college.undefineName='aaa'
//删除
delete state.college.name
15.vuex module模块()分割vuex多个state,getters…更方便管理
index.js:
const moduleA={
state:{
counter:10
},
getters:{
},
mutations:{
},
actions:{
}
}
//引入模块
const store= createStore({
mutations:{},//...
modules:{
a:moduleA
}
})
//在页面中使用这个模块的数据
{{$store.state,a.counter}}
16.getter怎么使用(模块分割 直接拿到state操作)
getters{
getCount(state){
return state.count+'xxx';
}
}
//页面使用
{{state.getters.getCount}}