通过 Prop 向子组件传递数据
模版写法:
1 2 3 4
| Vue.component('v-h1', { props: ['msg'], template: `<h1>{{ msg }}</h1>` });
|
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>组件基础</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script> </head> <body> <div id="app"> <v-h1 msg="我是标题"></v-h1> </div> <script type="text/javascript"> Vue.component('v-h1', { props: ['msg'], template: `<h1>{{ msg }}</h1>` }); new Vue({ el: '#app' }); </script> </body> </html>
|
监听子组件事件
在我们开发组件时,它的一些功能可能要求我们和父级组件进行沟通。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>组件基础</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script> </head> <body> <div id="app"> <div :style="{ fontSize: fontSize + 'em' }"> <v-p @big-font="fontSize++"></v-p> </div> </div> <script type="text/javascript"> Vue.component('v-p', { template: ` <div> <p>我是标题</p> <button @click="$emit('big-font')">放大文字</button> </div> ` }); new Vue({ el: '#app', data() { return { fontSize: 1 } } }); </script> </body> </html>
|
通过上面的代码可以发现,子组件可以通过调用内建的$emit方法并传入事件名称来触发一个事件,代码片段:
1 2 3 4 5
| <!-- 子组件 --> <button @click="$emit('big-font')">放大文字</button>
<!-- 父组件 --> <v-p @big-font="fontSize++"></v-p>
|
使用事件抛出一个值
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>组件基础</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script> </head> <body> <div id="app"> <div :style="{ fontSize: fontSize + 'em' }"> <v-p @big-font="fontSize += $event"></v-p> </div> </div> <script type="text/javascript"> Vue.component('v-p', { template: ` <div> <p>我是标题</p> <button @click="$emit('big-font', 0.1)">放大文字</button> </div> ` }); new Vue({ el: '#app', data() { return { fontSize: 1 } } }); </script> </body> </html>
|
代码片段:
1 2 3 4 5
| <!-- 子组件 --> <button @click="$emit('big-font', 0.1)">放大文字</button>
<!-- 父组件 --> <v-p @big-font="fontSize += $event"></v-p>
|
跟上面的例子做对比可以发现,使用事件抛出一个值时,只需在$emit上添加多一个参数即可,接收时使用$event进行接收。
通过插槽分发内容
在编写组件的过程中,有时我们希望组件里面能自己定义一些HTML元素,这时我们可以使用<slot>实现。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>组件基础</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script> </head> <body> <div id="app"> <v-demo> <p style="color: red;">我是内容</p> </v-demo> </div> <script type="text/javascript"> Vue.component('v-demo', { template: ` <div> <h1>我是标题</h1> <slot></slot> </div> ` }); new Vue({ el: '#app' }); </script> </body> </html>
|