Vuex简单使用流程

作者: 李佳明先生 | 来源:发表于2019-04-03 17:57 被阅读10次

    什么是Vuex?

    Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension,提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。

    如何使用?
    一、安装

    npm install vuex --save

    二、配置

    src下新建store,新建store.js
    然后代码如下:

    import Vue from 'vue';
    import Vuex from 'vuex';
    
    Vue.use(Vuex);
    let store = new Vuex.Store({
        // 1. state,类似于储存全局变量的容器
        state:{
           isPhone:false
        },
    
        // 2. getters,提供用来获取state数据的方法
        getters:{
            getType(){
                return state.isPhone
            }
        },
        // 3. actions
        // 提供与后台接口打交道的方法,并调用mutations提供的方法
        actions:{
            
        },
        // 4. mutations,常用于设置state数据
        mutations:{
            setIsPhone(state,type){
              state.isPhone=type
              console.log(state.isPhone);
            }
        }
    });
    
    export default store;
    

    这份代码里掺杂了例子,使用方法会以举例子的方式来告诉大家。这里的需求是通过函数判断屏幕大于是否小于750,如果小于,则isPhone为true,div显示,反之,则为false,div不显示

    三、全局引用

    store.js引入到main.js

    import store from './store/store'
    
    new Vue({
      el: '#app',
      store, //把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
      components: { App },
      template: '<App/>'
    })
    
    四、如何在页面里使用
    computed:{
          //每当 this.$store.state.isPhone变化的时候, 都会重新求取计算属性,并且触发更新相关联的 DOM。
          isPhone:function () {
            return this.$store.state.isPhone
          }
        },
    
    <div v-if="isPhone"></div>
    

    1. 在组件中这样使用
    import store from '../store/store'
    
      methods: {
        resize:function () {
          window.innerWidth<=750? this.isPhone=true:this.isPhone=false;
          store.commit('setIsPhone',this.isPhone)
        }
      }
    

    store.commit的第一个参数,你要触发mutations里的函数的函数名,第二个参数,你想要传递的数据

    END

    ps:如果项目的数据非常庞大的话,目录结构请参考官网说明
    最后放上官方的图例:

    相关文章

      网友评论

        本文标题:Vuex简单使用流程

        本文链接:https://www.haomeiwen.com/subject/irgzbqtx.html