vue使用datePicker如何让日历一直显示

1,074 阅读1分钟

vue2使用elementUI2如何让el-date-picker一直显示日历

想要实现效果如下图:
image.png
首先要解决的是el-picker-panel面板一直显示的问题,官方文档没有,直接百度。
百度查到的结果都是这样的:

<template>
    <el-date-picker ref="datePick" @blur="keepOpen"></el-date-picker>
</template>
<script>
export default{
    methods: {
        keepOpen() {
            this.$refs.datePick.focus(); //触发焦点
        }
    }
}
</script>

el-date-picker失去焦点后调用方法重新获取焦点。
image.png
还有这种操作?
这种肯定是不行的,我又百度了半天,给的都是这种,用就用吧。
第二天,果然不出我所料,出问题了,哈哈哈。
image.png
使用这个组件的页面有个el-input搜索框,想要测试下输入查询,结果怎么点el-input都无法触发focus。这要能点的了那可就真出bug了。
想想怎么补救吧,首先想到的补救方式如下:

<template>
    <el-date-picker ref="datePick" name="custom-date-picker" @blur="keepOpen"></el-date-picker>
</template>
<script>
export default{
    methods: {
        keepOpen() {
            let isFocus = true;
            // 判断页面上的所有输入框 custom-date-picker 除外 都加上onblur方法
            let inputAll = document.getElementsByTagName('input');
            inputAll.forEach(item => {
                if(item.name != 'custom-date-picker') {
                    item.onblur = () => this.$refs.datePick.focus()
                    if (item == document.activeElement) isFocus = false;
                }
            });
            if(isFocus) this.$refs.datePick.focus(); //触发焦点
        }
    }
}
</script>

定义isFocus遍历,控制el-date-picker是否聚焦,获取页面上所有的input,遍历为每个input添加失焦事件,如果已有input获取焦点isFocus设置为false。 但这样只能可以先测试了,要是这样的功能上线leader非得怼死我。
image.png
之前一直没有看源码的习惯,抱着试一试的态度去看下源码,没想到还真让我找到了。 首先先去src目录下的index.js,找到了DatePicker的引用。

image.png

进去后里面还有一层引用

image.png

找到最后发现就一个DatePicker引用的组件还挺多

image.png

最主要的组件是这个picker.vue,打开直接翻到watch这里

image.png

watch监听了pickerVisible属性,pickerVisible的默认值为false,如果pickerVisible为true会执行this.showPicker()
this.valueOnOpen赋值的操作源码属性上这样注释的

image.png

大致意思是,picker打开时的值,用于确定是否更改
然后写上看效果。

<template>
    <el-date-picker ref="datePick" @blur="keepOpen"></el-date-picker>
</template>
<script>
export default{
    methods: {
        keepOpen() {
            this.$refs.datePick.showPicker();
        }
    }
}
</script>

完美解决。

image.png