加,减功能使用了两种不同方式 ,效果相同,详细信息请查看Vuex官方文档.
1.安装
// html页面引入
<script src="/path/to/vue.js"></script>
<script src="/path/to/vuex.js"></script>
npm install vuex --save 或者 yarn add vuex
2.使用
①: src 目录下新建store文件夹,在store文件夹下新建index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
// 存储数据
state: {
count: 0
},
// 只有mutations中可以修改数据
//不能执行异步操作
mutations: {
add(state) {
state.count++
},
// 传参
addN(state, step) {
state.count += step
},
sub(state) {
state.count--
},
subN(state, step) {
state.count -= step
}
},
// 处理异步操作
// 触发mutations
actions: {
addAsync({ commit }) {
setTimeout(() => {
commit('add')
}, 1000)
},
addAsyncN({ commit }, step) {
setTimeout(() => {
commit('addN', step)
}, 1000)
},
subAsync({ commit }) {
setTimeout(() => {
commit('sub')
}, 1000)
},
subAsyncN({ commit }, step) {
setTimeout(() => {
commit('subN', step)
}, 1000)
}
},
// 类似计算属性
//对store中的数据进行加工处理,不会修改state中的数据
getters: {
showNum: state => {
return '当前数字为[' + state.count + ']'
}
// showNum(state) {
// return '当前数字为[' + state.count + ']'
// }
},
modules: {}
})
②: 添加功能 新建Add.vue
<template>
<div>
<h1>购物车数量 + </h1>
<!-- <h3>当前数为:{{ $store.state.count }}</h3> -->
<h3>{{ $store.getters.showNum }}</h3>
<button class="btn" @click="handleAdd()">+1</button>
<button class="btn" @click="handleAddN()">+N</button>
<button class="btn" @click="handleAddAsync()">+1Async</button>
<button class="btn" @click="handleAddNAsync()">+NAsync</button>
</div>
</template>
<script>
export default {
data() {
return {}
},
methods: {
// commit 触发motution中的方法
handleAdd() {
this.$store.commit('add')
},
handleAddN() {
this.$store.commit('addN', 3)
},
// dispatch专门处理action中函数 异步
handleAddAsync() {
this.$store.dispatch('addAsync')
},
handleAddNAsync() {
this.$store.dispatch('addAsyncN', 5)
}
}
}
</script>
<style>
.btn{
margin: 0 5px;
}
</style>
③: 减去功能 新建Sub.vue
<template>
<div>
<h1>购物车数量 - </h1>
<!-- <h3>当前数为:{{ count }}</h3> -->
<h3>{{ showNum }}</h3>
<button class="btn" @click="sub()">-1</button>
<button class="btn" @click="subN(2)">-N</button>
<button class="btn" @click="subAsync()">-1Async</button>
<button class="btn" @click="subAsyncN(4)">-NAsync</button>
</div>
</template>
<script>
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex' // 要引入
export default {
data() {
return {}
},
computed: {
// state 和 getter 映射到计算属性
// 字符串数组
...mapState(['count']),
...mapGetters(['showNum'])
},
methods: {
// mutations 和 action 映射到方法
...mapMutations(['sub', 'subN']),
...mapActions(['subAsync', 'subAsyncN'])
}
}
</script>
<style>
.btn{
margin: 0 5px;
}
</style>