回顾
以前我们在做这个新闻列表的时候,是一个写死的数据
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数据:
我们要根据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条数据了
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。