【青训营】组件入门

45 阅读2分钟

这是我参与「第四届青训营 」笔记创作活动的的第8天 

重点内容

  • 组件概述
  • 组件基本结构
  • 组件注册
  • 组件使用
  • 组件间的数据传递

组件概述

前面我们已经简单介绍了组件以及基础指令,这一章开始详细介绍组件的使用

组件可以让我们把UI划分为功能独立的模块,进行业务处理时只用考虑涉及到的组件,提高了代码的可读性,减少了开发和维护的难度。 通常来说,我们把页面划分为组件层层嵌套的树状结构。组件的嵌套方式类似与我们嵌套HTML元素。

组件的基本结构

通常我们会把组件放在一个SFC文件中,比如:

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

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

组件注册

如果一个组件希望被被其它页面或者组件使用,首先要进行注册,注册方式有两种,分别是全局注册和局部注册

全局注册:通过vue实例的create app()方法,可以让组件在全局可用

import { createApp } from 'vue'

const app = createApp({})

app.component(
  // 注册的名字
  'MyComponent',
  // 组件的实现
  {
    /* ... */
  }
)

SFC全局注册:

import MyComponent from './App.vue'
import ComponentAComponentBComponentC from './App.vue'
app.component('MyComponent', MyComponent)


//链式调用
app
  .component('ComponentA', ComponentA)
  .component('ComponentB', ComponentB)
  .component('ComponentC', ComponentC)

//模板中使用
<ComponentA/>
<ComponentB/>
<ComponentC/>


全局注册缺点:

  1. 全局注册,但并没有被使用的组件无法在生产打包时被自动移除 (也叫“tree-shaking”)。如果你全局注册了一个组件,即使它并没有被实际使用,它仍然会出现在打包后的 JS 文件中。
  2. 全局注册在大型项目中使项目的依赖关系变得不那么明确。在父组件中使用子组件时,不太容易定位子组件的实现。和使用过多的全局变量一样,这可能会影响应用长期的可维护性。

局部注册:比起全局注册,局部注册更容易维护,需要在使用它的父组件中显式导入,并且需要在components对象中声明,局部注册梗易维护,结构更加清晰:

<script>
import ComponentA from './ComponentA.vue'

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

<template>
  <ComponentA />
</template>

使用组件

如果想在组件中使用其它组件,首先要在想要调用的组件设置暴露选项,之后在使用的组件中声明引入该组件,然后放在components对象中,最后在模板中进行使用,理论上组件可以被使用无数次,如:

<script>
import ButtonCounter from './ButtonCounter.vue'

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

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

组件间的数据传递

组件之间可以通过props进行数据传递,想要传递的数据首先需要在props中进行声明:

export default {
  props: ['foo'],
  created() {
    // props 会暴露到 `this` 上
    console.log(this.foo)
  }
}

如果需要限定想要传入props的类型,提高可维护性,还可以通过对象的方式声明:

export default {
  props: {
    title: String,
    likes: Number
  }
}

使用:<组件名 props名=props值/>,如:

<BlogPost title="My journey with Vue" />