vue笔记 Vuex

2017-06-03  本文已影响67人  路路有话说

先上文档
自己的理解,就是存一些数据方便调用

安装方法

npm install vuex --save-dev

它必须以插件的方式进行引用

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

使用方法

index.js 中

const vuex_store=new Vuex.Store({
    state:{
        user_name:"",
    },
    mutations:{
        showUserName(state)
        {
            alert("显示一下"+state.user_name)
        }
    },
})

username.vue 中
userNameChange 方法中添加
  this.$store.state.user_name=this.username;

定义一个 vuex

const vuex_store=new Vuex.Store({})

应用级的状态集中放在 store 中。

添加属性

 state:{
        user_name:"",
    },

改变状态的方式是提交mutations,这是个同步的事务。

就是 添加方法

  mutations:{
        showUserName(state)
        {
            alert("显示一下"+state.user_name)
        }
    },

异步逻辑应该封装在action 中。

暂时未用到

在这里我们定义了一个 user_name

给这个属性赋值 this.$store.state.user_name=this.username;
调用 showUserName方法
this.$store.commit("showUserName");


有一些数据我们只需要请求一遍,并把它保存起来,而不是每次进到页面中都刷新

index.js 中添加
 state:{
        user_name:"",
        newsList:[]
    },
newlist.vue 中修改

  export default{
        created(){
            if(this.$store.state.newsList.length == 0 ){
                this.$http.post("http://域名/newslist.php").then(function (res) {
                    console.log("请求成功 绑定数据")
                    this.$store.state.newsList =  res.body
                },function (r) {
                    console.log(r)
                    console.log("请求失败")
                })
            }
        }
    }

注意这里接口仅允许了 post 所以使用 post 请求

newslist.php 代码如下

<?php 
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST');
header('Access-Control-Allow-Headers:x-requested-with,content-type');
$res = '[ {"newsid":"101","pubtime":"2016-10-02","title":"QFix 探索之路 —— 手Q热补丁轻量级方案 ","desc":"QFix是手Q团队近期推出的一种新的Android热补丁方案,在不影响App运行时性能>(无需插桩去preverify)的前提下有效地规避了","isshow":true},  {"newsid":"102","pubtime":"2016-10-01","title":"大规模排行榜系统实践及挑战 ","desc":" 如何支持业务接近接入,数万乃至几十万级排行榜自动化申请调度?选择什么样的存储引擎?怎样避免各业务资源抢占? ","isshow":false},{"newsid":"103","pubtime":"2016-09-28","title":"BitBucket Cloud新增Git大文件存储Beta支持 ","desc":"Git LFS背后的基本理念是将大型二进制文件存储在并行存储中,>而Git库只包含到那些文件的轻量级引用","isshow":true},{"newsid":"104","pubtime":"2016-09-30","title":"飞天进化,互联网、数据和计算的聚变 ","desc":"阿里巴巴技术委员会主席王坚发布的新书《在线》,被外界视作阿里巴巴技术体系总设计师的王坚出版的第一本著作,吸引了众多参会者的兴趣","isshow":true}]';

header('Content-Type:application/json; charset=utf-8');
exit($res);

允许跨域请求,设置返回为 json 格式, utf-8 编码
返回值 赋给 newsList this.$store.state.newsList = res.body
上方模板循环中 需要求改一下数据源

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

新增需求 根据 isshow 属性判断 该条数据是否显示

index.js 中添加
 getters: {
        getNews(state){
            return state.newsList.filter(function (news) {
                return news.isshow;
            })
        }
    }

newslist.vue 中修改
v-for="news in this.$store.getters.getNews"

新增需求 详情页要求可以实现点赞功能

其实就是 请求一个数据,并刷新到界面上

index.js 中添加
agree 方法,传入对象,及 newsid  id 作为数据传给服务器端 
context 调用 方法 setAgree  刷新页面中的 agree 值
 mutations:{
        setAgree(state,agreeNum)
        {
            state.newsdetail.agree=agreeNum;
        }
    },
    actions:{
        agree(context,_newsid)
        {
            //在这进行ajax请求,获取 点赞后的agree字段属性值
            Vue.http.post(
                "http://aleen.sololi.net/news.php",
                {newsid:_newsid},{emulateJSON:true}
                ).then(
                    function(res){
                        context.commit("setAgree",res.body.agree)
                    },function(){
                }
                )
        }
    },

newsdetail.vue 中 修改
在创建页面的时候 请求 news 的数据 并存入 state 中
点击点赞按钮时 调用上方 agree 方法 ,并将当前 newsid 传过去
this.$store.dispatch 调用 index 中的方法
  created()
        {
            this.$http.get("域名/news.php?newsid="+this.$route.params.newsid)
                    .then(function(res){
                        this.$store.state.newsdetail=res.body
                        console.log(res);
                    },function(rs){
                        console.log(rs)
                        console.log("请求失败")
                    })
        },
        methods:{
            submitAgree()
            { this.$store.dispatch("agree",this.$store.state.newsdetail.newsid)
            }
        }
    }

将 登录和新闻模块分开

所有模块都写在一个文件中导致这个文件特别大, 不方便管理 所以将其分开来,看一下文档

简单来说就是将index.js const vuex_store=new Vuex.Store({替换成下方的内容 并将
user 相关代码移到 ./../store/modules/UserModules"
news 相关代码移到 ./../store/modules/NewsModiles

import  UserModule from "./../store/modules/UserModules"
import  NewsModule from "./../store/modules/NewsModiles"
const vuex_store=new Vuex.Store({
    modules: {
        users: UserModule,
        news: NewsModule
    }
})

但是移动完成之后 发现页面报错 或者 不显示
需要将 .vue文件中 类似 this.$store.state.user_name = this.username;的地方替换成为
this.$store.state.users.user_name = this.username;
即添加上对应的modules 名即可

上一篇下一篇

猜你喜欢

热点阅读