源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2022-06-01 05:45 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Vuex利用state保存新闻数据实例
[img]http://files.jb51.net/file_images/article/201706/2017062815405036.png[/img] 回顾 以前我们在做这个新闻列表的时候,是一个写死的数据
  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"
[img]http://files.jb51.net/file_images/article/201706/2017062815405037.png[/img] [b]数据过滤[/b] 处理服务器返回来的数据,比如我们这里news.PHP 的返回的json数据:
[u]复制代码[/u] 代码如下:
[{"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;
      })
    }
  }
})

[code]getters [/code]专门写了一个方法,做了数据过滤处理,保留isdeleted为false 的记录。 那么我们在组件模板上循环的时候也要修改一下了:
v-for="news in this.$store.getters.getNews"
[img]http://files.jb51.net/file_images/article/201706/2017062815405138.png[/img]    过滤之后,只有2条数据了 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部