组件封装(学习记录)

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>
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值