基础
混入 (mixins) 是一种分发 Vue 组件中可复用功能的非常灵活的方式。混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被混入该组件本身的选项。
其实就是写一个没有 template 的 Vue Component
// 定义一个混入对象 var myMixin = { created: function () { this.hello() }, methods: { hello: function () { console.log('hello from mixin!') } } } // 定义一个使用混入对象的组件 var Component = Vue.extend({ mixins: [myMixin] }) var component = new Component() // => "hello from mixin!"
break_table_point
考虑到现公司项目重度使用 table, 并期望 table 出现纵向滚动条时, 能够固定 thead.
现大部分开源 table component 实现这一效果的方式, 都是向该组件传递 高度 , 例如:
<c-table :height="600"></c-table>
-
因此我们需要这样一个 mixins, 帮助我们在所有使用 table 并需要固定高度的视图组件中,即时 的计算出 高度, 这样一个 minxins, 我称其为 break_table_point.
-
即时的计算高度: 页面渲染完毕, 页面伸缩时,都能动态并且正确的返回 table 所需高度
-
为了达到此效果, 我们的 HTML 布局结构, 必须保证一致, 例如:
<!-- 页头 --> <header class="wrapper-header"></header> <!-- 主体布局 --> <div class="wrapper-content"> <div class="wrapper-form"> <!-- warapper-form 容器中放入 form 组件--> <c-form></c-form> </div> <div class="wrapper-table"> <!-- wrapper-table 容器中放入 table 组件 --> <c-table></c-table> </div> <div class="wrapper-pagination"> <!-- wrapper-pagination 容器中放入 pagination 组件 --> <c-pagination></c-pagination> </div> </div> <!-- 页尾 --> <div class="wrapper-footer"></div>
// break_table_point.js export const breakpoint = { data() { return { // 视口高度初始值 clientHeight: 0, // table 高度初始值 tableHeight: 0, }; }, computed: { // 通过 computed 即时计算出相应高度 $breakpoint() { let result = { 'clientHeight': this.clientHeight, 'tableHeight': this.tableHeight, }; return result; }, }, methods: { _updateDimensions() { // 获取视口高度 this.clientHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); // 各个容器的高度 const headerHeight = document.querySelector('.wrapper-header').offsetHeight const footerHeight = document.querySelector('.wrapper-footer').offsetHeight const formHeight = document.querySelector('.wrapper-form').offsetHeight const paginationHeight = document.querySelector('.wrapper-pagination').offsetHeight // table 高度 = 视口高度 - 各个容器高度总和 let tableHeight = this.clinetHeight - ( headerHeight + footerHeight + formHeight + paginationHeight) // 设置一个最小高度 500 px (tableHeight < 500) && (tableHeight = 500); // 设置 tableHeight // 此时 computed 会根据自身特性, 计算 $breakpoint this.tableHeight = tableHeight; }, }, mounted() { // 为 window 对象绑定 resize 事件 this.$nextTick(() => { this._updateDimensions(); window.addEventListener('resize', this._updateDimensions, { 'passive': true }); }); }, destroyed() { // 组件销毁时, 移除 resize 事件监听 window.removeEventListener('resize', this._updateDimensions); }, };
// 在组件中导入 break_table_point mixins import breakpoint from "break_table_point" export default { mixins: [breakpoint] /** 此时组件已有拥有混入中的 computed computed: { $breakpoint: { clinetHeight:0, tableHeight: 0, } } **/ }
<!-- 为 table 组件传入 tableHeight --> <c-table :width="$breakpoint.tableHeight"></c-table>