使用vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
在项目中用到了全屏,但是全屏后,主页中的表格没有重新计算高度,而全屏这个功能又是写在子组件当中,所以考虑用vuex,在state里定义高度这个变量。
第一步,是要npm install vuex。
第二步,main.js文件里:

        import Vuex from 'vuex';
        import store from './store';
        Vue.use(Vuex);
        new Vue({
            el: '#app',
            router,
            store,
            components: { App },
            template: '<App/>'
      })

第三步,建立store文件夹,建立index.js文件:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state={
    height:''
};
const mutations ={
    figure:state =>{ 
        state.height=parseInt(document.body.clientHeight) - 180;
        console.log("figure",state.height)
    }
};
const actions={
    figure:context=>{
        context.commit({type:'figure'})
    }
}
// 创建 store 实例
export default new Vuex.Store({
    state,
    mutations,
    actions,
})

第四步,分发actions

<Table border class="table_tb" :height="height" :columns="columns12" :data="data6">
mounted(){
        this.dispatch();
},
computed:{
      height(){  //height就是定义的变量
            return this.$store.state.height;//计算属性会将数据进行缓存,数据变化后就将数据动态返回
      }
},
methods:{
      dispatch(){
            this.$store.dispatch('figure');
      }
}

第五步,在子组件页面,也需要重新计算高度,所以也需要分发actions

methods:{
         handleChange () {
            this.handleFullscreen();
           setTimeout(() => {//异步等待全屏函数执行完,再执行此代码
              this.$store.dispatch('figure');
         }, 100);
       }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容