父组件的代码如下:
<template>
<el-button type="primary" @click="focus">聚焦</el-button>
<MyInput v-model="msg" ref="myInputRef"></MyInput>
</template>
<script setup lang="ts">
import MyInput from './MyInput.vue'
import { ref } from 'vue'
const myInputRef = ref()
const msg = ref('111')
//点击聚集也同时可以聚焦到子组件的input框
const focus = () => {
console.log(MyInput)
myInputRef.value.focus()
}
</script>
子组件MyInput 的代码如下:
<template>
<div>
hello World
</div>
<el-input ref="inputRef" v-bind="$attrs"></el-input>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const inputRef = ref()
</script>
<style scoped>
</style>
如何让子组件的input中ref的方法暴露出来呢
使用defineExpose的方法暴露子组件的方法
父组件代码如下:
<template>
<el-button type="primary" @click="focus">聚焦{{ msg }}</el-button>
<MyInput v-model="msg" ref="myInputRef">
<template #prepend>
<el-button>前置</el-button>
</template>
<template #append>
<el-button>后置</el-button>
</template>
</MyInput>
</template>
<script setup lang="ts">
import MyInput from './MyInput.vue'
import { ref } from 'vue'
const myInputRef = ref()
const msg = ref('111')
//点击聚集也同时可以聚焦到子组件的input框
const focus = () => {
console.log(MyInput)
myInputRef.value.focus()
}
</script>
子组件代码如下:
<template>
<div>
hello World
</div>
<el-input ref="inputRef" v-bind="$attrs">
<!-- 插槽 slotProps:插槽的作用域值-->
<template v-for="(_,slot) in $slots" :key="slot" #[slot]="slotProps">
<slot :name="slot" :v-bind="slotProps"></slot>
</template>
</el-input>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const inputRef = ref()
//采用代理的方法把子组件所有的方法暴露出去
defineExpose(
new Proxy({}, {
get(target, key) {
return inputRef.value?.[key]
},
has(target, key) {
return key in inputRef.value
}
})
)
</script>
<style scoped>
</style>
网友评论