栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

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

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

回顾新闻详细页

很早我们的新闻详情页是在news-detail.vue 组件里,获取服务器数据,然后把数据保持到组件的data 里,既然我们已经用到了vuex,学习了它的state,我们就应该想到把返回的数据交给state 来存储。

1.首先在Vuex.Store 实例化的时候:

  state:{
    user_name:"",
    newslist:[],
    newsdetail:{}
  },

增加一个newsdetail 对象,newslist 数组是我们前面用来保存新闻列表数据的。

2.下面就要看在news-detail.vue 组件里,怎么请求数据,然后交给newsdatail :



通过this.$store.state.newsdetail = res.body; 就把服务器返回的新闻详细数据保存起来了。

3.那么模板上怎么展示?


  {{this.$store.state.newsdetail.title}}{{this.$store.state.newsdetail.pubtime}}
  

点赞数:{{this.$store.state.newsdetail.agree}}

{{this.$store.state.newsdetail.desc}}

这里我们要来实现一个点赞功能

点击“点赞”按钮,就更改点击数。

其实就是更改newsdetail 里的agree 属性。

本文参考文档:https://vuefe.cn/vuex/actions.html

import Vuex from 'vuex';
Vue.use(Vuex);

const vuex_store = new Vuex.Store({
  state:{
    user_name:"",
    newslist:[],
    newsdetail:{}
  },
  mutations:{
    showUserName(state){
      alert(state.user_name);
    },
    setAgree(state,agreeNum){
      state.newsdetail.agree = agreeNum;
    }
  },
  actions:{
    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(){})
    }
  },
  getters:{
    getNews(state){
      return state.newslist.filter(function (news) {
 return !news.isdeleted;
      })
    }
  }
})

在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 方法呢?

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

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



 
 



 

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/86706.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号