工作实战:Vue关于ElementUI二次封装的问题

文章介绍了在Vue.js中处理组件间属性、插槽和ref引用的方法。通过v-bind使用$attrs实现属性的批量传递,$slots用于处理插槽内容,包括作用域插槽。同时,展示了如何将子组件的方法绑定到实例上,以便于父组件通过ref引用操作。
摘要由CSDN通过智能技术生成

第一个问题:属性的传递

解决方法:用v-bind="$attrs"批量属性传值的方法,学过react的都知道,类似于{…props}批量传值。有的属性可能需要二次处理,可以使用props接收,props过来的属性,不会出现在$attrs里了。你可以单独处理后再放回elementui的原生组件里了

// MyInput.vue

<template class="my-input">
	<el-input v-bind="$attrs"></el-input>
</template>

<style scoped>
.my-input{
	transition:0.3s;
}

.my-input:hover,
.my-input:focus-within{
	filter:drop-shadow(0 0 3px raba())
}
</style>
// App.vue
<template>
	<div>
		<MyInput v-model="data"></MyInput>
	</div>
</template>

<script setup>
import MyInput from './components/MyInput.vue'

const data = ref("")

</script>

第二个问题:插槽的传递

解决方法:用$slots批量传递插槽,同时要考虑作用域插槽的传递

// MyInput.vue

<template class="my-input">
	<el-input v-bind="$attrs">
		<template v-for="(value,name) in $slots" #[name]="slotData"> // 这里的slotData是el-input组件提供的数据
			<slot :name="name" v-bind="slotData || {}"></slot>
		</template>
	</el-input>
</template>

<style scoped>
.my-input{
	transition:0.3s;
}

.my-input:hover,
.my-input:focus-within{
	filter:drop-shadow(0 0 3px raba())
}
</style>
// App.vue
<template>
	<div>
		<MyInput v-model="data">
			<template #prepend>
				<el-select placeholder="Select" style="width:115px">
					<el-option label="Key1" value="1" />
					<el-option label="Key2" value="2" />
				</el-select>
			</template>
			<template #append>
				<el-button :icon="Search">
			</template>
		</MyInput>
	</div>
</template>

<script setup>
import MyInput from './components/MyInput.vue'

const data = ref("")

</script>

第三个问题:ref引用的问题

解决方法:将子组件的方法给绑定到子组件的实例上,然后获取子组件的实例就可,注意组合式和声明写法是有区别的

<template class="my-input">
	<el-input ref="inp" v-bind="$attrs"></el-input>
</template>

<script>
 // 声明式写法
 export default {
	mounted(){
		const entries = Object.entries(this.$refs.inp)
		for(const [key,value] of entries){
			this[key] = value;
		}
	}	
 }
</script>

<script setup>
	// 组合式写法
	const exposeMethods = {}
	const entries = Object.entries(this.$refs.inp)
	for(const [key,value] of entries){
		exposeMethods[key] = value;
	}
	defineExpose(exposeMethods)
</script>

<style scoped>
.my-input{
	transition:0.3s;
}

.my-input:hover,
.my-input:focus-within{
	filter:drop-shadow(0 0 3px raba())
}
</style>
// App.vue
<template>
	<div>
		// 暴漏的是MyInput组件的实例对象
		<MyInput v-model="data" ref="inputRef"></MyInput>
	</div>
</template>

<script setup>
import MyInput from './components/MyInput.vue'

const data = ref("")
const inputRef = ref(null) 

</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值