1、组件 MyInput.vue
$slots传递过来的值:
<template>
<div class="my-input">
// (1)希望v-model能直接传递过来(所有属性和事件的传递), 使用v-bind="$attrs"
<el-input v-bind="$attrs">
// (2)当前组件有哪些插槽就传递哪些,使用$slots拿到传递过来的所有插槽
// (3) 作用域插槽 el-input 组件会向这个插槽传递一些数据,数据应该#[name] = “slotData”接收
<template v-for="(value,name) in $slots" #[name]="slotData">
// 接收到的数据需要传递给引用它的页面
<slot :name="name" v-bind="slotData"></slot>
</template>
</el-input>
</div>
</template>
<script>
export default {
mounted(){
// 把所有属性名和属性值提到当前实例里面去
const entries = Object.entries(this.$refs.inp)
for(const [key,value] of entries ){
this[key] = value
}
}
}
</script>
2、引用组件 MyInput.vue
<template>
<div>
// 传递的v-model
// (4)给组件ref属性 但实际希望他绑定在el-input上(主要用里面的方法)
<MyInput ref = "inputRef" v-model="data" placeholder="地址">
<template #prepend>
默认插槽内容1
</template>
<template #append>
默认插槽内容2
</template>
</MyInput>
</div>
</template>
<script setup>
import { ref } from 'vue'
import MyInput from './components/MyInput.vue'
const data = ref('')
const inputRef = ref(null)
onMounted(()=>{
console.log(inputRef.value) // 这样子就能拿到了里面的方法
inputRef.value.focus()
})
</script>