vuex

npm install vuex --save-dev

import Vuex from 'vuex';

Vue.use(Vuex);

const vuex_store = new Vuex.Store({

state:{ user_name:"" },

mutations:{

showUserName(state){

alert(state.user_name);

}

} })

let myvue = new Vue({

el:".container",

store:vuex_store, //注入到vue router:routerConfig,

});

<template>

<div class="form-group">

<label class="col-sm-2 control-label">用户名</label>

<div class="col-sm-10">

<input type="text" v-uname="username" v-model="username" v-on:change="userNameChange" class="form-control" :placeholder="username">

</div>

</div>

</template>

<script>

export default{

props:["placeholder"],

data:function () {

return { username:"" }

},

methods:{

userNameChange(){

//this.$emit("childChange","username",this.username)

this.$store.state.user_name = this.username; }

}

}

</script>

当点击提交按钮时候,弹出用户名 
user-submit.vue

<template>
    <div class="form-group">
        <div class="col-sm-10 col-sm-offset-2">
            <button type="button" v-on:click="submit" class="btn btn-default">提交</button>
        </div>
    </div>
</template>

<script>
    export default{
        methods:{
            submit(){
                //alert(this.$parent.$data.username +"==="+ this.$parent.$data.userarea);
                this.$store.commit("showUserName");
            }
        }
    }
</script>


从服务器获取数据

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

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"



操作vuex数据

点击“点赞”按钮,就更改点击数。 
其实就是更改newsdetail 里的agree 属性。

本文参考文档:https://vuefe.cn/vuex/actions.html

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

const  vuex_store = new Vuex.Store({
    state:{
        user_name:"",
        newslist:[],
        newsdetail:{}
    },
    mutations:{
        showUserName(state){
            alert(state.user_name);
        },
        setAgree(state,agreeNum){
            state.newsdetail.agree = agreeNum;
        }
    },
    actions:{
        agree(context,newsid){
            // 进行请求,获取点赞后的agree字段属性值
            Vue.http.post("http://localhost/agree.php",{newsid:newsid},{emulateJSON:true}).then(function (res) {
                // 处理业务
                // 调用上面setAgree方法更新点赞数
                context.commit("setAgree",res.body.agree);
            },function(){})
        }
    },
    getters:{
        getNews(state){
            return state.newslist.filter(function (news) {
                return !news.isdeleted;
            })
        }
    }
})

news-detail.vue 组件全部代码:

<template>
    <div class="news-detail">
        <div class="row">
            <div class="page-header">
                <h2>{{this.$store.state.newsdetail.title}}<small>{{this.$store.state.newsdetail.pubtime}}</small></h2>
                <p>点赞数:{{this.$store.state.newsdetail.agree}} <button class="btn btn-success" @click="submitAgree">点赞</button></p>
                <p>{{this.$store.state.newsdetail.desc}}</p>
            </div>
        </div>
    </div>
</template>



<script>
    export default{
        // 创建的时候[生命周期里]
        created(){
            this.$http.get("http://localhost/newsdetail.php?id="+this.$route.params.newsid).then(function(res){
                this.$store.state.newsdetail = res.body;
            },function(res){
                // 处理请求失败
            });
        },
        methods:{
            submitAgree(){
                // 组件了调用actions里定义的agree方法
                this.$store.dispatch("agree",this.$store.state.newsdetail.id)
            }
        }
    }
</script>
后台增加点赞数


将多个模块组件分开引用

2.UserModules.js:

export default{
    state:{
        user_name:""
    },
    mutations:{
        showUserName(state){
            alert(state.user_name);
        }
    },
}

3.NewsModules.js:

export default{
    state:{
        newslist:[],
        newsdetail:{}
    },
    mutations:{
        setAgree(state,agreeNum){
            state.newsdetail.agree = agreeNum;
        }
    },
    actions:{
        agree(context,newsid){
            // 进行请求,获取点赞后的agree字段属性值
            Vue.http.post("http://localhost/agree.php",{newsid:newsid},{emulateJSON:true}).then(function (res) {
                // 处理业务
                // 调用上面setAgree方法更新点赞数
                context.commit("setAgree",res.body.agree);
            },function(){})
        }
    },
    getters:{
        getNews(state){
            return state.newslist.filter(function (news) {
                return !news.isdeleted;
            })
        }
    }
}

4.这2步做好之后,我们已经把用户和新闻分离了,分离之后怎么引入呢?

import UserModule from "./../store/modules/UserModule";
import NewsModule from "./../store/modules/NewsModule";
const  vuex_store = new Vuex.Store({
    modules:{
        users:UserModule,
        news:NewsModule
    }
})    
5.之后我们需要修改组件 

需要修改此处的代码,需要加上我们的模块名,修改之后:

<script>
    export default{
        created(){
            if (this.$store.state.news.newslist.length == 0){
                // 请求服务器获取数据
                this.$http.get("http://localhost/news.php").then(function (res) {
                    this.$store.state.news.newslist = res.body;
                },function (res) {
                    // 请求失败处理
                })
            }
        }
    }
</script>

NewsModule.js中,我们是通过Vue.http.post() 来获取服务器数据的,可能会找不到Vue,所以在这个文件头部,我们再次引入一下:

import Vue from "vue";


 
 
原文地址:https://www.cnblogs.com/cina33blogs/p/6879462.html