Vuex利用state保存新闻数据实例

2019-11-20,,

回顾

以前我们在做这个新闻列表的时候,是一个写死的数据

  export default{
    data(){
      return{
        newslist:[
          {newsid:"101",pubtime:"2016-10-29",title:"探索之路",desc:"是手机团队的探索之路"},
          {newsid:"102",pubtime:"2016-10-28",title:"系统之战",desc:"如何支持业务解决"},
          {newsid:"103",pubtime:"2016-10-27",title:"大文件存储",desc:"背后的你不得不知的技术"},
          {newsid:"104",pubtime:"2016-10-26",title:"飞天进化",desc:"阿里巴巴技术委员会"},
        ]
      }
    },
  }

然后在模板上循环:

<div class="page-header" v-for="news in newslist">

今天我们来学习从服务器获取数据

news-list.vue:

  export default{
    created(){
      if (this.$store.state.newslist.length == 0){
        // 请求服务器获取数据
        this.$http.get("http://localhost/news.php").then(function (res) {
          this.$store.state.newslist = res.body;
        },function (res) {
          // 请求失败处理
        })
      }
    }
  }

组件生命周期(创建)里请求服务器获取数据,然后保存到了state 里:

this.$store.state.newslist = res.body;

newslist 在实例化Vuex.Store 的时候定义,入口文件index.js里:

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

组件模板上就要这样循环了:

v-for="news in this.$store.state.newslist"

数据过滤

处理服务器返回来的数据,比如我们这里news.PHP 的返回的json数据:

复制代码 代码如下:
[{"id":101,"pubtime":"2016-10-29","title":"探索之路","desc":"是手机团队的探索之路","isdeleted":false},{"id":102,"pubtime":"2016-10-29","title":"排行榜","desc":"如何支持业务接入?选择什么存储引擎?","isdeleted":false},{"id":103,"pubtime":"2016-10-29","title":"大文件存储","desc":"讲大型二进制文件存储,只包含那些文件的轻量级引用","isdeleted":true}]

我们要根据isdeleted 做数据过滤,不多说,先看代码:

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

const vuex_store = new Vuex.Store({
  state:{
    user_name:"",
    newslist:[]
  },
  mutations:{
    showUserName(state){
      alert(state.user_name);
    }
  },
  getters:{
    getNews(state){
      return state.newslist.filter(function (news) {
        return !news.isdeleted;
      })
    }
  }
})

getters 专门写了一个方法,做了数据过滤处理,保留isdeleted为false 的记录。

那么我们在组件模板上循环的时候也要修改一下了:

v-for="news in this.$store.getters.getNews"

  

过滤之后,只有2条数据了

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

您可能感兴趣的文章:

  • 详解vuex commit保存数据技巧
  • Vue中保存数据到磁盘文件的方法
  • vue生成token并保存到本地存储中
  • Vue中保存用户登录状态实例代码
  • Vue项目使用localStorage+Vuex保存用户登录信息

《Vuex利用state保存新闻数据实例.doc》

下载本文的Word格式文档,以方便收藏与打印。