0%

vue组件基础

基本示例

组件是可复用的 Vue 实例, 且带有一个名字, 我们可以通过 new Vue 创建的 Vue 跟实例中, 把这个组件当做自定义元素来使用
组件与 new Vue 接受相同的选项

组件的 data 必须是一个函数, 它返回一个对象的独立的拷贝
组件注册可分为 全局注册局部注册

1
2
3
4
5
6
7
8
Vue.component('hello-world', {
data() {
return {
msg: 'Hi! Vue',
}
},
template: '<div> {{ msg }} </div>',
})

组件的复用

组件可以进行任意次数的复用, 每个组件都会各自维护它的实例

1
2
3
4
5
<div id="app">
<hellp-world></hellp-world>
<hellp-world></hellp-world>
<hellp-world></hellp-world>
</div>

组件的组织

一个应用会以一颗嵌套的组件树的形式来组织:
component

通过 Prop 向子组件传递数据

Prop 是可以在组件上注册的一些自定义 attribute, 当一个值传递给一个 prop attribute 的时候, 他就变成了那个组件实例的一个属性.
我们可以用一个 props 选项将其包含在该组件可接受的 prop 列表中

1
2
3
4
Vue.component('hello-world', {
props: ['title'],
template: '<h3> {{ title }}</h3>',
})

单个根元素

每个组件必须只有一个根元素

当构建一个子组件的时候, 模板内最终包含的内容远不止一个标题, Vue 要求每个组件必须只有一个根元素, 可以将模板的内容包裹在一个父元素内.

1
2
3
4
5
6
7
8
9
10
// parent 父组件
<div class="parent">
<child />
</div>

// child 子组件
<div class="child">
<h3>标题</h3>
<p>内容</p>
</div>

监听子组件事件

有时候, 我们需要在子组件内部传递一些内容到父元素
Vue 实例提供了一个自定义事件的系统来解决这个问题, 父组件可以像处理 native DOM 事件一样通过 v-on 监听子组件实例的任意事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 父组件 接受一个由子元素提交的自定义方法
<div class="parent">
<child v-on:myEmit="handleEmit" />
</div>

// 子组件 传递一个自定义事件
<child v-on:click="$emit('myEmit')">
子组件
</child>

<hr />

// 父组件 接受一个由子元素提交的自定义方法
<div class="parent">
<child v-on:myEmit="handleEmit" />
</div>

// 子组件 自定义方法可以通过第二个参数进行传递
<child v-on:click="$emit('myEmit', true)">
子组件
</child>

在组件上使用 v-model

自定义事件也可以用于创建支持 v-model 的自定义输入组件

1
<my-input v-model="searchText" />

等价于

1
<my-input v-bind:value="searchText" v-on:input="searchText = $event" />

为了让它正常工作, 这个组件内的 <input> 必须:

  • 将其 value attribute 绑定到一个名叫 value 的 prop 上
  • 在其 input 事件被触发时, 将新的值通过自定义的 input 事件抛出

通过插槽分发内容

和 HTML 元素一样, 我们经常需要向一个组件传递内容

1
2
3
4
5
6
7
8
9
<!-- 父组件使用子组件 -->
<alert-box>
<span>插槽插入内容</span>
</alert-box>
<!-- 子组件 -->
<alert-box>
<!-- 插槽插入内容会替换下面的slot标签 -->
<slot></slot>
</alert-box>

动态组件

有的时候, 在不同的组件之间进行动态切换时非常有用的
我们可以通过 Vue 的<component>元素加一个特殊的isattribute 来实现
currentTabComponent 可以包括

  • 已注册组件的名字
  • 一个组件的选项对象
1
2
// 组件会在 currentTabComponent 改变时改变
<component v-bind:is='currentTabComponent'></component>
请作者喝杯咖啡