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

2020-06-14 06:05:46易采站长站整理

这里写图片描述

回顾

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


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 做数据过滤,不多说,先看代码: