VUE利用vuex模拟实现新闻点赞功能实例

2020-06-14 06:00:12易采站长站整理

})
}
}
})

actions 
里定义了一个方法
agree 
发送网络请求,获取最新的点赞数。

同时

mutations 
里定义了一个
setAgree 
方法,用来同步页面上的点赞数。


agree(context,newsid){
// 进行请求,获取点赞后的agree字段属性值
Vue.http.post("http://localhost/agree.php",{newsid:newsid},{emulateJSON:true}).then(function (res) {
// 处理业务
// 调用上面setAgree方法更新点赞数
context.commit("setAgree",res.body.agree);
},function(){})
}

重点说明:这里发送http请求,和组件里不一样,需要注意。

那么,组件里怎么调用这里的agree 方法呢?


<button class="btn btn-success" @click="submitAgree">点赞</button>


methods:{
submitAgree(){
// 组件了调用actions里定义的agree方法
this.$store.dispatch("agree",this.$store.state.newsdetail.id)
}
}

news-detail.vue 组件全部代码:


<template>
<div class="news-detail">
<div class="row">
<div class="page-header">
<h2>{{this.$store.state.newsdetail.title}}<small>{{this.$store.state.newsdetail.pubtime}}</small></h2>
<p>点赞数:{{this.$store.state.newsdetail.agree}} <button class="btn btn-success" @click="submitAgree">点赞</button></p>
<p>{{this.$store.state.newsdetail.desc}}</p>
</div>
</div>
</div>
</template>

<script>
export default{
// 创建的时候[生命周期里] created(){
this.$http.get("http://localhost/newsdetail.php?id="+this.$route.params.newsid).then(function(res){
this.$store.state.newsdetail = res.body;
},function(res){
// 处理请求失败
});
},
methods:{
submitAgree(){
// 组件了调用actions里定义的agree方法
this.$store.dispatch("agree",this.$store.state.newsdetail.id)
}
}
}
</script>

这里写图片描述 

后端程序增加点赞数,这里就不赘述了。只需返回一个json对象:


{"status":"success","agree":100}