VueX实现不同组件的数据共享 数据持久化

vuex的使用:
    1、src目录下面新建一个vuex的文件夹

    2、vuex 文件夹里面新建一个store.js

    3、安装vuex  
        cnpm install vuex --save

    4、在刚才创建的store.js引入vue  引入vuex 并且use vuex

        import Vue from 'vue'
        import Vuex from 'vuex'

        Vue.use(Vuex)

    5、定义数据
            /*1.state在vuex中用于存储数据*/
            var state={

                count:1
            }

    6、定义方法   mutations里面放的是方法,方法主要用于改变state里面的数据

        var mutations={

            incCount(){

            ++state.count;
            }
        }

    7、优点类似计算属性   ,  改变state里面的count数据的时候会触发 getters里面的方法 获取新的值 (基本用不到)
        var getters= {     
            computedCount: (state) => {
            return state.count*2
            }
        }
    8、 Action 基本没有用
        Action 类似于 mutation,不同在于:
        Action 提交的是 mutation,而不是直接变更状态。
        Action 可以包含任意异步操作。
        var actions= {
            incMutationsCount(context) {    /*因此你可以调用 context.commit 提交一个 mutation*/   
            context.commit('incCount');    /*执行 mutations 里面的incCount方法 改变state里面的数据*/
            }
        }
    暴露
        const store = new Vuex.Store({
            state,
            mutations,
            getters,
            actions
        })
        export default store;

组建里面使用vuex:
        1.引入 store
             import store from '../vuex/store.js';
        2、注册
             export default{
                data(){
                    return {               
                       msg:'我是一个home组件',
                    value1: null,                
                    }
                },
                store,
                methods:{
                    incCount(){
                      
                    this.$store.commit('incCount');   /*触发 state里面的数据*/
                    }
                }
                }
        3、获取state里面的数据  
            this.$store.state.数据
        4、触发 mutations 改变 state里面的数据
            this.$store.commit('incCount');
        5、触发 actions里面的方法
            this.$store.dispatch('incCount');
        6、{{this.$store.getters.computedCount}}  获取 getters里面方法返回的的数据
示列代码如下

src/components/

<template>
    <!-- 所有的内容要被根节点包含起来 -->
    <div id="home" style="padding:20px;">    
       我是首页组件  -- {{this.$store.state.count}} ----{{this.$store.getters.computedCount}}          
        <button @click="incCount()">增加数量+</button>      
    </div>
</template>
<script>
    //1. 引入store   建议store的名字不要变
    import store from '../vuex/store.js';
    //2.注册
    export default{
        data(){
            return {               
                msg:'我是一个home组件',
                value1: null,             
            }
        },
        store,
        methods:{
            incCount(){
                //改变vuex store里面的数据

                //this.$store.commit('incCount');   /*触发 mutations 改变 state里面的数据*/

                this.$store.dispatch('incMutationsCount');   /*触发 actions里面的方法   */
            }
        }
    }

</script>
<style lang="scss" scoped>    
</style>

<template>    
    <div id="news">    
       我是新闻组件   --{{this.$store.state.count}}       
        <br>
        <button @click="incCount()">增加数量</button>
                <br><br>
                <br><br>
                <ul>
                    <li v-for="item in list">                    
                        {{item.title}}
                    </li>
                </ul>                        
    </div>
</template>
<script>
    //1. 引入store
    import store from '../vuex/store.js';
    export default{
        data(){
            return {               
               msg:'我是一个新闻组件',
               list:[]             
            }
        },
        store,
        methods:{
            incCount(){
                this.$store.commit('incCount');
            },
            requestData(){
                  //请求数据
                    var api='http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1';
                    this.$http.get(api).then((response)=>{
                        console.log(response);
                        //注意this指向
                        this.list=response.body.result;
                        //数据放在store里面
                        this.$store.commit('addList',response.body.result);
                    },function(err){
                            console.log(err);
                    })
            }
        },mounted(){
            //判断 store里面有没有数据
            var listData=this.$store.state.list;
            console.log(listData.length);
            if(listData.length>0){
                    this.list=listData;
            }else{
                 this.requestData();
            }
        }
    }
</script>

<style lang="scss" scoped>   
    .list{
        li{
            height:3.4rem;
            line-height:3.4rem;
            boder-bottom:1px solid #eee;
            font-size:1.6rem;
            a{
                color:#666;               
            }
        }
    }
</style>
<template>    
    <div id="news">    
       我是用户组件        
    </div>
</template>
<script>
    export default{
        data(){
            return {               
               msg:'我是一个新闻组件'  ,                  
            }
        }       
    }

</script>
<style lang="scss" scoped>
</style>

src/router/router.js

import Vue from 'vue';

//配置路由
import VueRouter from 'vue-router';
Vue.use(VueRouter);

//1.创建组件
import Home from '../components/Home.vue';
import News from '../components/News.vue';
import User from '../components/User.vue';

//2.配置路由   注意:名字

const routes = [
    { path: '/home', component: Home },
    { path: '/news', component: News, name: 'news' },
    { path: '/user', component: User },
    { path: '*', redirect: '/home' }   /*默认跳转路由*/
]

//3.实例化VueRouter  注意:名字

const router = new VueRouter({
    mode: 'history',   /*hash模式改为history*/
    routes // (缩写)相当于 routes: routes
})
//5 <router-view></router-view> 放在 App.vue
export default router;

src/vuex/store.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
/*1.state在vuex中用于存储数据*/
var state={
    count:1,
    list:[]
}

/*2.mutations里面放的是方法,方法主要用于改变state里面的数据
*/
var mutations={
    incCount(){
        ++state.count;
    },
    addList(state,data){

        state.list = data;
    }
}
/*3、优点类似计算属性   ,  改变state里面的count数据的时候会触发 getters里面的方法 获取新的值 (基本用不到)*/
var getters= {
   
    computedCount: (state) => {
        return state.count*2
    }
}

/*
4、 基本没有用

Action 类似于 mutation,不同在于:

Action 提交的是 mutation,而不是直接变更状态。
Action 可以包含任意异步操作。
*/
var actions= {
    incMutationsCount(context) {    /*因此你可以调用 context.commit 提交一个 mutation*/
            
        context.commit('incCount');    /*执行 mutations 里面的incCount方法 改变state里面的数据*/
    }
}

//vuex  实例化 Vuex.store   注意暴露
const store = new Vuex.Store({
    state,
    mutations,
    getters,
    actions
})
export default store;

App.vue

<template>
  <div id="app"> 
    <header class="header">
      <router-link to="/home">首页</router-link>
      <router-link to="/news">新闻</router-link>
       <router-link to="/user">用户</router-link>
    </header>
    <hr>
    <router-view></router-view>
  </div>
</template>
<script>
   export default {     
      data () { 
        return {
         
         msg:'你好vue'
        }
      }
     
    }
</script>
<style lang="scss">
  .header{
    height:4.4rem;
    background:#000;
    color:#fff;
    line-height:4.4rem;
    text-align:center;
    a{
      color:#fff;
      padding:0 2rem
    }
  }
</style>

mian.js

import Vue from 'vue';
import App from './App.vue';

//引入公共的scss   注意:创建项目的时候必须用scss
import './assets/css/basic.scss';   
//请求数据

import VueResource from 'vue-resource';

Vue.use(VueResource);
//配置路由
import router from './router/router.js';

//4、挂载路由

new Vue({
  el: '#app',
  router,
  render: h => h(App)
})

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。