前言
随着技术的快速发展,前端为了快速开发,我们一般会接入像elementui这样的库,以element为例,一些组件无法满足我们的需求,就需要做二次封装。今天想着尝试利用vue的函数式组件做一下二次封装。
先来看一个最简单的demo来补充点基础知识
// demo.vue
<template>
<div class="demo">
<DeInput @debounce="debounce" maxlength='5' @blur="inputBlur"/>
</div>
</template>
<script>
import DeInput from './DeInput'
export default {
name: 'Demo',
components: {
DeInput
},
methods: {
debounce(value) {
console.log('防抖后:', value)
},
inputBlur() {
console.log('失去焦点')
}
}
}
// deinput.vue
<template>
<div>
<el-input v-model="inputValue" @input="deInput"></el-input>
</div>
</template>
<script>
export default {
data() {
return {
inputValue: ''
}
},
methods: {
deInput() {
this.$emit('debounce', this.inputValue)
}
}
}
如果去运行这段代码就会发现inputBlur这个函数根本没有执行,maxlength这个属性也没有生效,这是因为@blur和
maxlength是el-input内部方法和属性。如果想要调用,就需要做透传,换句话说就是让el-input知道它的方法或者属性被调用。其实只要vue提供的\ a t t r s 和 attrs和 attrs和listeners属性即可。
- a t t r s : 包 含 了 父 作 用 域 中 不 作 为 p r o p 被 识 别 ( 且 获 取 ) 的 a t t r i b u t e 绑 定 ( c l a s s 和 s t y l e 除 外 ) 。 当 一 个 组 件 没 有 声 明 任 何 p r o