1、vuex状态管理--购物车数量增减
2019-04-26 本文已影响0人
蕉下客_661a
GIF.gif
<template>
<div>
<h3 style="margin-bottom:20px;">1、购物车数量增减</h3>
<div class="quantity">
<a href="javascript:;" class="decrement" :class="disabled ?'disabled':'' " @click=decreaseNum(1) >-</a>
<input class="iTxt" v-model="changableNum" />
<a href="javascript:;" class="increment" @click=increaseNum(1) >+</a>
</div>
</div>
</template>
<script>
import { mapState,mapMutations} from 'vuex' //引入mapState、mapMutations映射函数
export default{
computed:{
...mapState({
changableNum:state => state.headerStatus.changableNum, //用模块headerStatus里的状态 changableNum
disabled:state => state.headerStatus.disabled
}),
methods:{
...mapMutations(['increaseNum','decreaseNum'])
}
}
</script>
vuex -- headerStatus.js模块 存放路径:store/modules/headerStatus.js
const state = {
changableNum:1,
disabled:true
}
const getters = {
}
const mutations = {
increaseNum(state,num){ //changableNum增加一个数
state.changableNum += num;
if(state.changableNum >1){
state.disabled = false;
}else{
state.disabled = true;
}
},
decreaseNum(state,num){ //changableNum减少一个数
if(state.changableNum > 1 ){
state.changableNum -= num;
if(state.changableNum <= 1 ){
state.disabled = true;
return false;
}
}
}
}
const actions = {
}
export default {
state,
getters,
mutations,
actions
}
这是store 文件夹下的index.js
用modules写法
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import headerStatus from './modules/headerStatus'
export default new Vuex.Store({
modules:{
headerStatus
}
})
css样式
.quantity{
position:relative;
display:inline-block;
width:80px;
height:22px;
background:#fff;
}
.increment,.decrement{
display:inline-block;
width:16px;
height:18px;
background:#fff;
border:1px solid #ccc;
color:#666;
padding:1px 0;
text-align:center;
}
.increment{
float:right;
border-left:0px;
}
.decrement{
float:left;
border-right:0;
}
.iTxt{
position:absolute;
left:17px;
top:0px;
display:inline-block;
width:42px;
height:18px;
line-height:18px;
border:1px solid #ccc;
text-align:center;
font-size:12px;
padding:1px;
}
.disabled{
color:#eee;
}