美文网首页
vuex状态管理器实现组件之间的传递

vuex状态管理器实现组件之间的传递

作者: Bonne_nuit | 来源:发表于2021-02-26 09:06 被阅读0次

    vuex状态管理器实现组件之间的传递

    组件间的传递除了props,emit等方法之外,还可以通过vuex进行传递,vuex一般适用于大中型项目,如果是小项目的话prop,emit等方法就足够用了,不然会显得项目繁琐。

    //向storage中存储数据
    this.$store.commit("setIHeight", document.documentElement.clientHeight);
    
    //store.js
    import Vue from 'vue'
    import Vuex from 'vuex'
    
    Vue.use(Vuex)
    
    export default new Vuex.Store({
      state: {
        keepAlive: ['index'], //路由缓存数组,存储每个页面的name
        iHeight: 0, //整体高度
        iWidth: 0, //整体宽度
        orgmanager1:""
      },
    
      mutations: {
         setKeepAlive: (state, keepAlive) => {
          state.keepAlive = keepAlive
        },
        addKeepAlive: (state, name) => {
          var k = state.keepAlive.indexOf(name);
          if (k == -1) {
            state.keepAlive.push(name);
          }
        },
        removeKeepAlive: (state, name) => {
          var k = state.keepAlive.indexOf(name);
          if (k > -1) {
            state.keepAlive.splice(k, 1);
          }
        },
        setIHeight: (state, value) => {
          state.iHeight = value;
        },
        setIWidth: (state, value) => {
          state.iWidth = value;
        },
        orgmanager1: (state, value) => {
          state.orgmanager1 = value;
        },
      },
      getters: {
        keepAlive: state => state.keepAlive,
        iHeight: state => state.iHeight,
        iWidth: state => state.iWidth,
      }
    })
    
    
    //获取storage数据的方法
    1.
    export default {
      name: 'App',  
      computed: {
        //缓存的保持状态数组  store
        keepAlive() {
          return this.$store.getters.keepAlive;
        },
        iHeight: {
          get: function() {
            return this.$store.getters.iHeight;
          },
          set: function() {}
        },
        iWidth: {
          get: function() {
            return this.$store.getters.iWidth;
          },
          set: function() {}
        }  
      }, 
      2.可直接用v-model做双向数据绑定
      <input v-model="$store.state.orgmanager1"  @click="open(1)" />
      3.
      const p = this.$store.state.orgmanager1;
    

    相关文章

      网友评论

          本文标题:vuex状态管理器实现组件之间的传递

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