- 什么是Vuex?
答:它是一个专为Vue.js应用程序开发的状态管理模式。状态指的是每个页面data()中的变量。
- 为什么使用Vuex?
答:当我们构建一个中大型的单页面应用程序时,Vuex可以更好的帮助我们在组件外部统一管理状态。有点类似全局变量,在任意网页中都能使用。
- 安装Vuex
cnpm i vuex
核心概念
State:是唯一的数据源,单一的状态树,存放状态
Getters:可以派生出一些新的状态。加工state成员给外界
Mutatuions:更改Vuex的store中的状态的唯一方法是提交mutatuion。
Actions:提交的是mutation,可以包含任何异步操作
Modules:面对复杂的应用程序,当管理的状态比较多时,我们需要Vuex的store对象分割成模块(moudles),模块化状态管理
Vuex工作流程
Vuex演示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vuex演示</title>
<script src="../node_modules/vue/dist/vue.js"></script>
<script src="../node_modules/vuex/dist/vuex.min.js"></script>
</head>
<body>
<div id="app">
<h2>{{msg}}</h2>
<a href="javascript:;" @click='add'>点击</a>
<counter></counter>
</div>
<script>
// 定义组件
const counter = {
template:`
<div>
<div> 点击数量:{{ count }} </div>
<div> actions触发:{{ num }}</div>
<div> 用户名:{{ userName }} </div>
</div>
`
,
// 实时计算
computed:{
count(){
return this.$store.state.count;
},
name(){
return this.$store.state.name;
},
num(){
return this.$store.state.num;
},
userName(){
return this.$store.getters.userName;
}
}
};
// vuex相当于一个数据存储的方式
const store = new Vuex.Store({
state:{ // 存放状态
count:10,
num:100,
name:'lwq'
},
getters:{ //可以对state中的成员加工后传递给外界
userName(state){
return state.name + ',Hello';
}
},
// mutations是操作state数据的方法的集合,比如对该数据的修改、增加、删除等等。
mutations:{
increment(state){
state.count++;
},
decrement(state){
state.num--;
},
updateName(state,username){
state.name=username;
}
},
actions:{ //由于直接在mutation方法中进行异步操作,将会引起数据失效。所以提供了Actions来专门进行异步操作,最终提交mutation方法
incrementAction(context){
context.commit("decrement")
},
}
});
new Vue({
el:"#app",
store:store, // 若名字相同,可以不用赋值
data:{
msg:"Vuex的使用"
},
components:{
counter
},
methods:{
add(){
this.$store.commit("increment"); // mutations的触发用commit
this.$store.commit("updateName",'bml'); // mutation的传值
this.$store.dispatch("incrementAction") // actions的触发用dispatch
}
}
})
</script>
</body>
</html>
网友评论