Vue3入门-04组件基础

Vue3入门-04组件基础

组件:组件允许我们将UI划分为独立的、可重用的部分,并且可以对每个部分进行单独的思考。在实际应用中,组件常常被组织成层层嵌套的树状结构。

请添加图片描述

在vue中组件占据着重要的地位,通过本章节先进行简单的入门,而后再进行细致的讲解。

本章主要包括:组件的定义、组件的使用、组件值的传递、组件事件的监听、插槽的使用、动态组件以及DOM模板解析注意事项。

选项式API

组件的定义

当使用构建步骤是,我们一般会将Vue组件定义在一个单独的.vue文件中,这被叫做单文件组件(Single File Compoent,简称SFC)。

<script>
export default {
  data() {
    return {
      count: 0
    }
  }
}
</script>

<template>
  <button @click="count++">You clicked me {{ count }} times.</button>
</template>

组件的使用

组件可以被多次重用

  1. 导入外部组件
  2. 在compoents中注册
  3. 在template中使用
<script>
import ButtonCounter from './ButtonCounter.vue'

export default {
  components: {
    ButtonCounter
  }
}
</script>

<template>
  <h1>Here is a child component!</h1>
  <ButtonCounter />
</template>

传递props值

通过props可以将父组件想要传递的值传递过去,父组件将值传递过去后,每一个子组件都会产生一个新的实例,所以每个组件中的值可能会不同。

实现方法:

  1. 在父组件中使用属性的赋值方式将值赋值给子组件
  2. 在子组件中定义props来接受参数
  3. 直接在子组件中使用子组件模板中使用

子组件:

<!-- BlogPost.vue -->
<script>
export default {
  props: ['title']
}
</script>

<template>
  <h4>{{ title }}</h4>
</template>

父组件

<BlogPost title="My journey with Vue" />
<BlogPost title="Blogging with Vue" />
<BlogPost title="Why Vue is so fun" />

监听事件

通过监听事件,父组件可以获得子组件触发的相应事件并且设置响应方法,比如子组件中如果触发click,父组件就可以捕获到事件并且执行响应方法。

实现步骤:

  1. 在父组件调用子组件时中设置响应方式
  2. 子组件中声明emits内容
  3. 在子组件的响应事件中设置$$emit(‘响应事件’)$

父组件

<template>
  <div :style="{ fontSize: postFontSize + 'em' }">
    <BlogPost
      v-for="post in posts"
      :key="post.id"
      :title="post.title"
      @enlarge-text="postFontSize += 0.1"
    ></BlogPost>
  </div>
</template>

子组件

<script>
export default {
  props: ['title'],
  emits: ['enlarge-text']
}
</script>

<template>
  <div class="blog-post">
	  <h4>{{ title }}</h4>
	  <button @click="$emit('enlarge-text')">Enlarge text</button>
  </div>
</template>

通过插槽来分配内容

一些情况下我们会希望能和HTML元素一样想组件中传递内容,就可以通过Vue自定义的<slot>来实现。

实现步骤:

  1. 在子组件中插入slot
  2. 在父组件中插入内容

父组件

<AlertBox>
  Something bad happened.
</AlertBox>

子组件

<template>
  <div class="alert-box">
    <strong>This is an Error for Demo Purposes</strong>
    <slot />
  </div>
</template>

<style scoped>
.alert-box {
  /* ... */
}
</style>

动态组件

在有一些场景会需要切换不同的组件,比如tab,可以通过Vue的component元素和特殊的isattribute实现。

<!-- currentTab 改变时组件也改变 -->
<component :is="currentTab"></component>

当使用component时切换不同的组件,被切换的组件就会被卸载。

DOM 模板解析注意事项

如果想在DOM中直接书写Vue模板,Vue则必须从DOM中获得字符串。

在DOM中有以下注意事项:

  • 区分大小写
  • 闭合标签必须和标签头成对出现,如<my-component></my-component>
  • 元素位置:li必须在ul或ol中,tr必须在table中
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值