时间:2021-07-01 10:21:17 帮助过:42人阅读
以上是vuex的官方文档对vuex的介绍,官方文档对vuex的用法进行了详细的说明。这里就不再细讲vuex的各个用法,写这篇博客的目的只是帮助部分同学更快地理解并上手vuex。
1. 安装
$ npm install vuex --save
2. 在main.js 主入口js里面引用store.js
3. 在store.js里引用Vuex
4. 在vue组件中使用
使用$store.commit('jia')区触发mutations下面的加减方法
<template>
<p class="hello">
<h1>Hello Vuex</h1>
<h5>{{$store.state.count}}</h5>
<p>
<button @click="$store.commit('jia')">+</button>
<button @click="$store.commit('jian')">-</button>
</p>
</p>
</template>
<!-- 加上scoped是css只在这个组件里面生效,为了不影响全局样式 -->
<style scoped>
h5{
font-size: 20px;
color: red;
}
</style>5. 查看演示

6. state访问状态对象
使用computed计算
<template>
<p class="hello">
<h1>Hello Vuex</h1>
<h5>{{count}}</h5>
<p>
<button @click="$store.commit('jia')">+</button>
<button @click="$store.commit('jian')">-</button>
</p>
</p>
</template>
<script>
import {mapState} from 'vuex'
export default{
name:'hello', //写上name的作用是,如果你页面报错了,他会提示你是那个页面报的错,很实用
// 方法一
// computed: {
// count(){
// return this.$store.state.count + 6
// }
// }
// 方法二 需要引入外部 mapState
computed:mapState({
count:state => state.count + 10
})
// ECMA5用法
// computed:mapState({
// count:function(state){
// return state.count
// }
// })
//方法三
// computed: mapState([
// 'count'
// ])
}
</script>7. mutations触发状态 (同步状态)
<template>
<p class="hello">
<h1>Hello Vuex</h1>
<h5>{{count}}</h5>
<p>
<button @click="jia">+</button>
<button @click="jian">-</button>
</p>
</p>
</template>
<script>
import {mapState,mapMutations} from 'vuex'
export default{
name:'hello', //写上name的作用是,如果你页面报错了,他会提示你是那个页面报的错,很实用
//方法三
computed: mapState([
'count'
]),
methods:{
...mapMutations([
'jia',
'jian'
])
}
}
</script>8. getters计算属性
getter不能使用箭头函数,会改变this的指向
在store.js添加getters
9. actions (异步状态)
在store.js添加actions
在组件中使用
<template>
<p class="hello">
<h1>Hello Vuex</h1>
<h5>{{count}}</h5>
<p>
<button @click="jia">+</button>
<button @click="jian">-</button>
</p>
<p>
<button @click="jiaplus">+plus</button>
<button @click="jianplus">-plus</button>
</p>
</p>
</template>
<script>
import {mapState,mapMutations,mapGetters,mapActions} from 'vuex'
export default{
name:'hello',
computed: {
...mapState([
'count'
]),
...mapGetters([
'count'
])
},
methods:{
// 这里是数组的方式触发方法
...mapMutations([
'jia',
'jian'
]),
// 换一中方式触发方法 用对象的方式
...mapActions({
jiaplus: 'jiaplus',
jianplus: 'jianplus'
})
}
}
</script>
<style scoped>
h5{
font-size: 20px;
color: red;
}
</style>10. modules 模块
适用于非常大的项目,且状态很多的情况下使用,便于管理
修改store.js

相关推荐:
实例分享Vue全家桶实践项目总结
使用React全家桶搭建一个后台管理系统实例详解
Vue2.0 全家桶开发的网页应用(参照吾记APP)
以上就是关于Vuex的全家桶状态管理的详细内容,更多请关注Gxl网其它相关文章!