Vuex速学篇:(2)利用state保存新闻数据

这里写图片描述

回顾

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

    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:"阿里巴巴技术委员会"},
                ]
            }
        },
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

然后在模板上循环:

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

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

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) {
                    // 请求失败处理
                })
            }
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

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

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

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

    state:{
        user_name:"",
        newslist:[]
    },
  • 1
  • 2
  • 3
  • 4

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

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

这里写图片描述

数据过滤

处理服务器返回来的数据,比如我们这里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}]
  • 1

我们要根据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;
            })
        }
    }
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

getters 专门写了一个方法,做了数据过滤处理,保留isdeleted为false 的记录。 
那么我们在组件模板上循环的时候也要修改一下了:

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

这里写图片描述
过滤之后,只有2条数据了

原文地址:https://www.cnblogs.com/snowhite/p/9134553.html