需求:
如圖 要求點擊收藏 更新狀態(tài)

image.png
思路:
后臺給的數(shù)據(jù)是一個大數(shù)組courseData['hotCourse':{},'newCourse':{},recommendCourse:{},'storeData':[]];每一個課程是一個組件,在課程組件上綁定一個click事件collect,觸發(fā)vuex的action事件collect,并傳入當(dāng)前課程的數(shù)據(jù),調(diào)入收藏和取消收藏的接口,接口成功調(diào)用mutation改變state的storeData數(shù)據(jù),頁面依賴數(shù)據(jù)改變更新視圖。
代碼如下:
頁面:
<div class="pro-list">
<proList
:list="$store.state.dataCourse"
@changePage="changePage" ref="proList"
:display="display"
@collect="collect" //組件定義的事件 collect:function(data){this.$store.dispatch('collect',data}},
@cancel="cancel">
</proList>
</div>
組件: (注意在collect事件上加上stop防止事件冒泡)
<template>
<div>
<ul v-if="list.length" class="data-hot">
<li v-for="(dataHot,index) in list" class="new-card" :key='index' @click.stop="$emit('changePage',dataHot)">
<div class="left mu-card-media">
<img :src='IMGURL+dataHot.course_picture' alt="">
<div class="modal"></div>
</div>
<div class="right">
<div class="title">{{dataHot.course_name}}</div>
<div>{{$store.state.counts}}</div>
<div class="data-hot-content new_content">{{dataHot.course_abstract}}</div>
<div class="dataHot-bottom card_bottom">
<span class="free" v-if="dataHot.pay">免費</span>
<span class="unfree" v-else>¥{{dataHot.course_price}}</span>
<div class="bottom-right">
<b v-if="display">
<span v-if="$store.state.storeData.indexOf(dataHot.course_id)==-1" class="collect" @click.stop="$emit('collect',dataHot)">收藏</span>
<span @click.stop="$emit('collect',dataHot)" class="collect isCollect" v-if="$store.state.storeData.indexOf(dataHot.course_id)!=-1">已收藏</span>
</b>
<span class="comment">{{dataHot.comment_num}}</span>
</div>
</div>
</div>
</li>
</ul>
</div>
</template>
vuex:
const state={
storeData:{},
}
const mutation={
// 收藏
changeCollect(state,payload){
if(state.storeData.indexOf(payload)==-1){
state.storeData.push(payload);
}else{
let index=state.storeData.indexOf(payload)
state.storeData.splice(index,1)
}
},
}
const action={
// 收藏&取消收藏
collect({commit},data){
let isCollect=(url,data)=>{
axios.post('/index/Activityapi/'+url,{
course_id:data.course_id
}).then(res=>{
if(res.data.code==1){
commit('changeCollect',data.course_id)
}else{
Vue.prototype.$toast.error('收藏失敗');
}
}).catch(err=>{
Vue.prototype.$toast.error('收藏失敗');
})
}
if(localStorage.getItem('token')){
if(state.storeData.indexOf(data.course_id)==-1){
isCollect('storeup',data)
}else{
isCollect('cancelStore',data)
}
}else{
router.push('login')
}
},
}