Vue3 组件篇

组件命名

组件的命名一般分为两种

  1. 在单文件组件中,推荐为子组件使用 PascalCase 的标签名,以此来和原生的 HTML 元素作区分。虽然原生 HTML 标签名是不区分大小写的,但 Vue 单文件组件是可以在编译中区分大小写的。我们也可以使用 /> 来关闭一个标签。
  2. 使用 kebab-case 形式并显式地关闭这些组件的标签。
<script setup>
import ButtonCounter from './ButtonCounter.vue'
</script>
<template>
  // 第一种
  <ButtonCounter />
  // 第二种
  <button-counter></button-counter>
</template>

组件参数的传递props

使用<script setup>语法糖时 defineProps defineEmits可以不用引入直接使用
prop 的名字很长,应使用 camelCase 小驼峰形式

// 子组件
<script setup>
// 字符串数组来声明
defineProps(['title'])
// 对象的形式
defineProps({
  title: String,
  likes: Number
})
// Ts使用
defineProps<{
  title?: string
  likes?: number
}>()
// 父组件中传递多个属性时,可以写一个没有名字的空对象,里面写多个参数 下面两者相等
const post = {
  id: 1,
  title: 'My Journey with Vue'
}
<BlogPost v-bind="post" />
<BlogPost :id="post.id" :title="post.title" />
// boolean类型的时候可以省略传递 两者相等
<BlogPost is-published />
<BlogPost :is-published="true" />
</script>

组件官网地址

组件插槽

在父组件中写dom插入子组件内
在父组件中可以获取子组件的数据(抛出),也可以访问到父组件的数据(在当前页面用)。

// 父组件 AlertBox组件的名字
<AlertBox>
  // 传递给子组件的内容 代替slot
  Something bad happened.
</AlertBox>
// 子组件
<template>
  <div class="alert-box">
    // 这里将被代替成写入的dom
    <slot />  // 会被替换为 Something bad happened.
  </div>
</template>

具名插槽 默认情况下插槽的名字是 default 可以省略不写,当多个插槽时,可以使用名字区分

// 定义名字
<slot name="header"></slot>
// 父组件中使用
<BaseLayout>
  <template v-slot:header>
    <!-- header 插槽的内容放这里 -->
  </template>
  // 两者等价,下面是简写
  <template #header>
    <!-- header 插槽的内容放这里 -->
  </template>
</BaseLayout>

组件数据抛出 父组件可以获取子组件的数据

定义两个变量 text count 接收子组件的数据
<slot :text="greetingMessage" :count="1"></slot>
父组件中使用
<MyComponent v-slot="{ text, count }"> 这里使用了解构赋值
  {{ text }} {{ count }}
</MyComponent>
----------------------------------------------------------------
// 定义插槽名字同时传递数据
<slot name="header" message="hello"></slot>
父组件中使用
<MyComponent>
  <template #header="{ message }">
    {{ message }}
  </template>
</MyComponent>
---------------------------------------------------------------
简单使用,复杂理解
对于第一个,我们改造一下
定义一个变量
const item = {
  text:'',
  count:'',
}
定义一个对象变量传递
<slot v-bind="item"></slot>
父组件中使用
<MyComponent v-slot="{ text, count }"> 这里使用了解构赋值
  {{ text }} {{ count }}
</MyComponent>

插槽官网

动态组件

在多个组件间作切换时,被切换掉的组件会被卸载。

<component :is="组件名字"></component>

组件注册

全局注册 局部注册

组件透传

官网地址

依赖注入

官网地址

组件 v-model

官网地址

posted @ 2023-07-26 11:18  LC蜗牛  阅读(131)  评论(0编辑  收藏  举报