组件实例
<div id="components-demo">
<button-counter></button-counter>
</div>
Vue.component('button-counter', {
data: function () {
return {
count: 0
}
},
template: '<button @click="count++">You clicked me {{ count }}
times.</button>'
});
new Vue({
el: '#components-demo'
})
- 组件化通信
1. 通过 Prop 向子组件传递数据
Prop 是你可以在组件上注册的一些自定义特性。当一个值传递给一个 prop 特性的时候,它就变成了那个组件实例的一个属性。一个组件默认可以拥有任意数量的 prop,任何值都可以传递给任何 prop。
<div id="blog-post-demo">
<blog-post
v-for="post in posts"
:key="post.id"
:title="post.title"
></blog-post>
</div>
Vue.component('blog-post', {
props: ['title'],
template: '<h3>{{ title }}</h3>'
});
new Vue({
el: '#blog-post-demo',
data: {
posts: [
{ id: 1, title: 'My journey with Vue' },
{ id: 2, title: 'Blogging with Vue' },
{ id: 3, title: 'Why Vue is so fun' }
]
}
})
2. 监听子组件事件
子组件可以通过调用内建的 $emit
方法 并传入事件名称来触发一个事件
<div id="blog-posts-events-demo">
<div :style="{ fontSize: postFontSize + 'em' }">
<blog-post
v-for="post in posts"
:key="post.id"
:post="post"
@enlarge-text="postFontSize += 0.1"
></blog-post>
</div>
</div>
Vue.component('blog-post', {
props: ['post'],
template: `
<div class="blog-post">
<h3>{{ post.title }}</h3>
<button @click="$emit('enlarge-text')">
Enlarge text
</button>
<div v-html="post.content"></div>
</div>
`
});
new Vue({
el: '#blog-posts-events-demo',
data: {
posts: [
{id: 0, title: "My journey with Vue", content: "...content..."},
{id: 0, title: "Blogging with Vue", content: "...content..."},
{id: 0, title: "Why Vue is so fun", content: "...content..."}
],
postFontSize: 1
}
});
- provide & inject
一个父组件向其所有子组件注入一个依赖,不论组件层次有多深,并在起上下游关系成立的时间里始终生效。
1. 定义父组件
<div id="blog-posts-events-demo">
<first></first>
</div>
new Vue({
el: '#blog-posts-events-demo',
provide() {
return {
message: "parent"
}
},
});
2. 定义子组件 first
Vue.component('first', {
template: `
<div class="blog-post">
{{message}}
<second></second>
</div>
`,
inject: ['message']
});
3. 定义子组件second
Vue.component('second', {
template: `
<div class="blog-post">
{{message}}
</div>
`,
inject: ['message']
});
运行之后:
- element-ui 组件库
- 实现表单验证组件