vue3基础-组件基础

根据组件实现内容的不同,一般可以分为以下几种类型

  1. 业务组件:这些组件是页面中特定业务逻辑的一部分,用于实现特定功能或展示特定数据。

  2. 基础组件:这些组件是页面中通用的、可重用的组件。

  3. 第三方组件:这些组件是由其他开发者或组织提供的,可以通过引入库或插件的方式使用。

未命名

使用组件

🎞️视频

1.定义组件

// /src/components/vButton.vue

<script setup>

</script>

<template>
    <button>按钮</button>
</template>

2.组件注册

局部注册:

在script中引入后即可直接在模板中使用,
局部注册的组件仅在当前文件中可以使用,如果其它文件也要使用该组件,
需要再次注册。

// /src/App.vue
<script setup>

import vButton from './components/vButton.vue'

</script>

<template>
    <vButton></vButton>
    <v-button></v-button>   // 使用时也可以将驼峰改为肉串
    <vButton/>              // 单闭合标签
</template>

全局注册:

全局注册的组件可以在全局中使用,
但并没有被使用的组件无法在生产打包时被自动移除 (也叫“tree-shaking”)。

// /src/main.js

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import vButton from './components/vButton.vue'

createApp(App)
.component('vButton', vButton)
.mount('#app')

组件传值

1.props

子组件可以通过defineProps来声明要接收的参数列表。
以下代码示例中注册了widthheight两个prop ,并且直接在模板中使用。

// /src/components/vButton.vue

<script setup>

defineProps(['width','height'])

</script>

<template>
    <button :style="{width,height}">按钮</button>
</template>

父组件在模板中给widthheight传递值

// /src/App.vue
<script setup>

import vButton from './components/vButton.vue'

</script>

<template>
    <vButton width="100px" height="30px"/>
    <vButton width="50px" height="50px"/>
</template>

插槽

1.默认插槽

使用slot标签就可以创建一个默认插槽,在下面的例子中,使用默认插槽来替换组件的文本

// /src/components/vButton.vue

<script setup>

defineProps(['width','height'])

</script>

<template>
    <button :style="{width,height}">
	<slot/>
    </button>
</template>

在父组件中,直接在vButton中填写dom内容就可以将内容替换在slot标签的位置上。

// /src/App.vue
<script setup>

import vButton from './components/vButton.vue'

</script>

<template>
    <vButton width="100px" height="30px">
 	这是一个按钮
    </vButton>
</template>

2.具名插槽

默认插槽只能满足一个插槽的情况,如果需要使用多个插槽就需要使用具名插槽。
在slot标签上添加name属性就定义好了一个具名插槽

// /src/components/vButton.vue

<script setup>

defineProps(['width','height'])

</script>

<template>
    <button :style="{width,height}">
	<slot name="icon"/>	
	<slot/>
    </button>
</template>
// /src/App.vue
<script setup>

import vButton from './components/vButton.vue'

</script>

需要替换具名插槽时使用 v-slot:定义的插槽name。
<template>
    <vButton width="100px" height="30px">
        <template v-slot:icon>
	  <img src="xxx" width="15" height="15">	
	</template>
 	这是一个按钮
    </vButton>
</template>
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值