Vue.js 学习之组件(上篇)

在 Vue.js 开发中,组件是一个非常重要的概念。它允许我们将一个复杂的页面拆分成多个可复用的小部分,提高代码的可维护性和复用性。本文将深入探讨 Vue.js 组件的基础知识,包括组件的定义、注册、使用等内容。

目录#

  • 组件的基本概念
  • 组件的定义
  • 组件的注册
    • 全局注册
    • 局部注册
  • 组件的使用
  • [组件的 props](#组件的 props)
    • [props 的基本使用](#props 的基本使用)
    • [props 的验证](#props 的验证)
  • 组件的事件
    • 自定义事件的触发
    • 自定义事件的监听

组件的基本概念#

组件是 Vue.js 中可复用的 Vue 实例。每个组件都有自己的模板、数据、方法等。通过组件,我们可以将页面拆分成多个独立的部分,每个部分负责特定的功能。

组件的定义#

在 Vue.js 中,我们可以使用 Vue.component 方法来定义一个全局组件,或者在 Vue 实例的 components 选项中定义局部组件。

全局注册#

Vue.component('my-component', {
  template: '<div>这是一个全局组件</div>'
});

局部注册#

new Vue({
  el: '#app',
  components: {
   'my-component': {
      template: '<div>这是一个局部组件</div>'
    }
  }
});

组件的注册#

全局注册#

全局注册的组件可以在任何 Vue 实例中使用。例如:

<div id="app">
  <my-component></my-component>
</div>

局部注册#

局部注册的组件只能在注册它的 Vue 实例中使用。例如:

<div id="app">
  <my-component></my-component>
</div>

组件的使用#

在模板中,我们可以像使用 HTML 标签一样使用组件。例如:

<template>
  <div>
    <my-component></my-component>
  </div>
</template>

组件的 props#

props 的基本使用#

props 是组件的属性,用于从父组件向子组件传递数据。在子组件中,我们可以通过 props 选项来声明接收的属性。例如:

Vue.component('child-component', {
  props: ['message'],
  template: '<div>{{ message }}</div>'
});

在父组件中使用:

<template>
  <div>
    <child-component message="Hello from parent"></child-component>
  </div>
</template>

props 的验证#

为了确保传递给组件的 props 符合要求,我们可以对 props 进行验证。例如:

Vue.component('child-component', {
  props: {
    message: {
      type: String,
      required: true
    }
  },
  template: '<div>{{ message }}</div>'
});

组件的事件#

自定义事件的触发#

在子组件中,我们可以使用 $emit 方法来触发自定义事件。例如:

Vue.component('child-component', {
  methods: {
    handleClick() {
      this.$emit('custom-event', 'Hello from child');
    }
  },
  template: '<button @click="handleClick">Click me</button>'
});

自定义事件的监听#

在父组件中,我们可以使用 v-on 指令来监听子组件触发的自定义事件。例如:

<template>
  <div>
    <child-component @custom-event="handleEvent"></child-component>
  </div>
</template>
<script>
export default {
  methods: {
    handleEvent(message) {
      console.log(message);
    }
  }
};
</script>

参考#