app开发定制在使用中的el-table时,app开发定制我们经常会用到fiexd属性,而使用了fixed属性之后,app开发定制就会容易在各种场景出现表格错位的问题。
查阅element-ui官网,发现官网提供了doLayout方法来解决这个问题
总结容易出现错位问题的几种场景及解决办法
1、数据更新后出现的错位问题
1.1 直接在数据赋值后执行doLayout方法
- this.data = data;
- // 在数据更新后执行
- this.$nextTick(() => {
- // myTable是表格的ref属性值
- if (this.$refs.myTable && this.$refs.myTable.doLayout) {
- this.$refs.myTable.doLayout();
- }
- })
1.2在生命周期updated里执行doLayout方法
- updated() {
- // myTable是表格的ref属性值
- if (this.$refs.myTable && this.$refs.myTable.doLayout) {
- this.$refs.myTable.doLayout();
- }
- }
2、浏览器窗口大小变化时出现的错位问题
- // 绑定window的onresize事件(注意,onresize事件只能有一个)
- window.onresize = () => {
- // myTable是表格的ref属性值
- if (this.$refs.myTable && this.$refs.myTable.doLayout) {
- this.$refs.myTable.doLayout();
- }
- }
3、当有多个Tab标签时,切换标签出现的错位问题
这时可以有多种解决方式
3.1 在组件守卫里执行doLayout方法
- beforeRouteEnter(to, from, next) {
- // myTable是表格的ref属性值
- if (this.$refs.myTable && this.$refs.myTable.doLayout) {
- this.$refs.myTable.doLayout();
- }
- //不能忘记这个哦
- next();
- }
3.2 如果使用了keep-alive,可以在activated里执行doLayout方法
- activated() {
- // myTable是表格的ref属性值
- if (this.$refs.myTable && this.$refs.myTable.doLayout) {
- this.$refs.myTable.doLayout();
- }
- }
3.3 也可以通过监听路由,在watch里执行doLayout方法
- watch: {
- $route() {
- this.$nextTick(() => {
- // myTable是表格的ref属性值
- if (this.$refs.myTable && this.$refs.myTable.doLayout) {
- this.$refs.myTable.doLayout();
- }
- })
- }
- }
如果当项目已经开发进入尾声,此时需要修改大量的文件,而我们可能更希望一次性解决这个问题,这个时候可以在App.vue里找到解决的思路
- <template>
- <div id="app">
- <router-view ref="appView"></router-view>
- </div>
- </template>
- <script>
-
- export default {
- data() {
- },
- watch: {
- $route() {
- //切换标签时
- this.handleRefreshTable();
- }
- },
- created() {
- let _this = this;
- //窗口改变时
- window.onresize = function () {
- _this.handleRefreshTable();
- };
- },
- updated() {
- //数据改变时
- this.handleRefreshTable();
- },
- methods: {
- handleRefreshTable() {
- this.$nextTick(() => {
- // 获取页面中已注册过ref的所有的子组件。
- let refList = this.$refs.appView.$refs;
- if (refList) {
- for (let i of Object.keys(refList)) {
- // 根据doLayout方法判断子组件是不是el-table
- if (refList[i] && refList[i].doLayout) {
- // 执行doLayout方法
- refList[i].doLayout();
- }
- }
- }
- })
- }
- }
- };
- </script>