首先引入vuex的js文件,注意它是依托于vue进行的,所以vuex的js文件要在vue的js文件下方引入
创建Vuex实例
vuex实例中有五个属性
vuex实例化以后,我们怎么去调用里面的内容呢?
在插值表达式中通过$store.state.变量名就可以获取state中的变量
要想使用mutations中的方法,我们要先创建一个事件,通过这个事件去调用里面的方法。不过要注意的是我们要通过commit去调用里面的方法
cli(){
// 调用mutations中的方法要使用commit
this.$store.commit("setName","helloKitty")
},
使用actions中的方法同样要通过事件去调用,与调用mutations中的方法不同的是,要使用dispatch去进行调用
cli2(){
// 调用actions中的方式要使用dispatch
this.$store.dispatch("setAge2",20)
},
使用getters的方法也很简单,就是在差值表达式里通过$store.getters.属性名进行调用
使用modules中的变量与方法也基本类似,不过要在前面加上模块的名字,详情可见案例
<div id="app">
<!-- 使用存放的变量 -->
{{$store.state.name}}--{{$store.state.age}}
<hr>
使用getters里的变量: {{$store.getters.intro}}
<hr>
<button @click="cli">调用mutations中方法</button> {{$store.state.name}}
<hr>
<button @click="cli2">调用actions中的方法</button> {{$store.state.age}}
<hr>
使用模块化中的变量 {{$store.state.childStore.name}}
<hr>
<button @click="cli3">使用模块化中的方法</button>
</div>
<script>
// 创建一个vuex实例中的模块
let childStore = { // 里面和vuex实例中一样,可以放五个属性
namespaced:true, // 开辟一个命名空间
state:{
name:"poppy",
age:2
},
mutations:{
getName(state,newValue){
console.log(state);
console.log(newValue);
}
}
}
// 2.实例化vuex
const store = new Vuex.Store({
state:{ // 存放变量,相当于vue实例中的data
name:"kitty",
age:3
},
mutations:{ // 数据操作,直接修改state里的值,只支持同步
setName(state,newValue){
console.log(state); // 打印state中的变量
console.log(newValue); // 传进来的新值
state.name=newValue
},
setAge(state,newValue){
state.age=newValue
}
},
actions:{ // 数据操作,不能直接修改state里的值,借用mutations中的方法来修改,支持异步
setAge2(context,newValue){ // context代表整个store,使用commit调用mutations中的方法
context.commit("setAge",newValue) // setAge 为mutations中的方法
}
},
getters:{ // 相当于vue中的计算属性
intro(state){
return "我叫"+state.name+"我今年"+state.age+"岁"
}
},
modules:{ // 模块化vuex,封装一套vuex,相当于在vuex实例中进行嵌套
childStore // childStore在外部进行声明 childStore:childStore 进行简写
}
})
new Vue({
el: '#app',
data() {
return {
}
},
methods: {
cli(){
// 调用mutations中的方法要使用commit
this.$store.commit("setName","helloKitty")
},
cli2(){
// 调用actions中的方式要使用dispatch
this.$store.dispatch("setAge2",20)
},
// 使用模块中的方法
cli3(){
console.log(1);
this.$store.commit("childStore/getName")
}
},
// 3.挂载
store,
watch:{
"$store.state.name"(e){ // 通过监听器去监听vuex中的变量
console.log(e);
}
}
});
</script>
补充:我们还可以使用监听器对vuex中的变量进行监听
// 完整的写法
// cli3(){
// console.log(1);
// this.$store.commit("childStore/getName")
// },
...Vuex.mapMutations({ // 简写
cli3: "childStore/getName"
}),
computed: {
// 完整的写法
// num1(){
// return "我叫"+this.$store.state.name
// },
...Vuex.mapState({ // 简写
num1:e=> "我叫" + e.name,
num2:e=> "我今年" + e.age
})
}