这节主要讲了 几个辅助函数,我贴了代码,很容易理解
<template>
<div class="hello">
<h1 v-if="is_show2">vuex小例子:点击切换文字的隐藏 </h1>
<a href="javascript:;" @click="dj">点我吧</a>
<a href="javascript:;" @click="dj2">mapMutations</a>
<a href="javascript:;" @click="dj3">异步的actions</a>
<a href="javascript:;" @click="dj4">actions的辅助函数</a>
</div>
</template>
<script>
//如果不想重复写10遍return this.$store.state,有个辅助函数。
// vue 提供了 mapState 辅助函数,它把state 直接映射到我们的组件中。
import {mapState} from "vuex";
//这个 mapGetters 同样是用来简化的,不需要重复写那么多 return this.$store.getters.id1;
import { mapGetters } from 'vuex'
//这个的作用是不用写很多次的 this.$store.commit('show_1');类似这样。。。
//可以直接 this.show_2() 这样的调用。。像函数一样的调用 映射出来而已
import { mapMutations } from 'vuex'
import { mapActions } from 'vuex' //道理跟上面一样理解就行
export default {
name: 'hello',
data () {
return {
// is_show:'true'
}
},
computed:{
qq(){
return this.$store.state.is_show;
},
qb(){
return this.text1; //这个 this.text1 就是...mapState下面的text1
},
qc(){
return this.$store.getters.id1; //单个获取 这里获取的就是text1的值了 id1是函数
},
//3个... 是对象展开符号
...mapState({
is_show2:'is_show', //直接映射state 对象中的is_show, 它相当于 this.$store.state.count,
text1:'text1'
}),
...mapGetters({
id1:'id1' //使用的时候就可以直接 {{id1}} 这样像普通data里的变量那样使用了
})
},
methods:{
dj(){
this.$store.commit('show_1');
},
dj2(){
this.show_2(); //这个就是下面映射出来的 show_2
},
dj3(){
this.$store.dispatch('yibu_1',{id:88});
},
dj4(){
this.yibu(); //这个就是下面映射出来的 show_2
},
...mapMutations({
show_2:'show_2'
}),
...mapActions({
yibu:'yibu_1'
})
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
下面是store.js 的代码
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//管理属性值
var state={
is_show: true, //默认显示,点击的时候再隐藏
text1:'测试111'
}
//管理方法函数
var mutations={
show_1(state) {
state.is_show =!state.is_show;
},
show_2(state,id){
console.log('测试maputations---'+id);
}
}
//这个相当于是 state的计算属性 的意思 跟computed差不多 获取状态值
var getters = {
id1:function(state,getters){
return state.text1;
}
}
// 异步的mutations ,Action 通过 store.dispatch 方法触发 store.dispatch('increment')
var actions={
yibu_1(store,id) {
// console.log(id);
store.commit('show_2',id.id); //然后再提交到mutations id传过来的是个对象
}
}
const store = new Vuex.Store({
state:state,
mutations:mutations,
getters:getters,
actions:actions
})
export default store
上面都是有注释的,相信大家很容易理解。。。。
以上是本人:bob,亲身经历实践,如有出错,欢迎指正,谢谢,QQ:2410024100