文章目录
1. 基本示例
<div id="app-1">
<button-counter></button-counter>
<button-counter></button-counter>
<button-counter></button-counter>
</div>
//全局定义组件
Vue.component('button-counter',{
//每个组件所需要的数据
data:function(){
return {
count:0
}
},
template:'<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})
new Vue({
el:"#app-1"
})
组件是可复用的 Vue 实例,且带有一个名字:在这个例子中是 <button-counter>
。我们可以在一个通过new Vue 创建的 Vue 根实例中
,把这个组件作为自定义元素来使用
效果图:
注意当点击按钮时,每个组件都会各自独立维护它的 count
。因为你每用一次组件,就会有一个它的新实例被创建。
1.1 data
必须是一个函数
一个组件的data 选项必须是一个函数
,因此每个实例可以维护一份被返回对象的独立的拷贝
:
注:data函数中一定要返回局部对象,如果返回的不是局部对象。每个 <button-counter>都引用一个对象就会导致点击任何一个按钮造成所有按钮的count加1
例子如下:
<div id="app-1">
<button-counter></button-counter>
<button-counter></button-counter>
<button-counter></button-counter>
</div>
var obj={ count:0 }
//全局定义组件
Vue.component('button-counter',{
//每个组件所需要的数据
data:function(){
return obj
},
template:'<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})
new Vue({
el:"#app-1"
})
2. 通过props
向子组件传递数据
当我们需要创建一个博文组件
的时候,如果你不能
向博文组件传递数据(内容、标题、作者)
的时候这个组件就是静态的根本无法使用。因此Vue提供了props
以供传递数据给组件
例子如下:
<div id="app-3">
<!--自定义的博文组件-->
<!--一个 prop 被注册之后,你就可以像这样把数据作为一个自定义 attribute 传递进来:-->
<blog-post title="My journey with Vue"></blog-post>
<blog-post title="Blogging with Vue"></blog-post>
<blog-post title="Why Vue is so fun"></blog-post>
</div>
Vue.component('blog-post',{
//自定义attribute
props:['title'],
template:'<h1>{{ title }}</h1>'
})
一个组件默认可以拥有任意数量的 prop,任何值都可以传递给任何 prop。
效果:
上述例子变形:
<div id="app-4">
<blog-post v-for="item in items" :key="item.id" :title="item.title">
</blog-post>
</div>
Vue.component('blog-post',{
props:['title'],
template:'<h1>{{ title }}</h1>'
})
new Vue({
el:"#app-4",
data:{
items:[
{id:1,title:"My journey with Vue"},
{id:2,title:"Blogging with Vue"},
{id:3,title:"Why Vue is so fun"}
]
}
})
3. 单根元素
当构建一个 组件时,你的模板最终会包含的东西远不止一个标题:
<h3>{{ title }}</h3>
最最起码,你会包含这篇博文的正文:
<h3>{{ title }}</h3>
<div v-html="content"></div>
然而如果你在模板中尝试这样写,Vue 会显示一个错误,并解释道every component must have a single root element (每个组件必须只有一个根元素)。
你可以将模板的内容包裹在一个父元素内,来修复这个问题,例如:
<template id="mytemplate">
<div>
<h3>{{ title }}</h3>
<div v-html="content"> </div>
</div>
</template>
Vue.component('blog-post',{
props:['title','content'],
template:"#mytemplate"
})
<template>是为了方便定义比较复杂的模板,在component中写字符串不易阅读和书写,通过ID查找模板
看起来当组件变得越来越复杂的时候,我们的博文不只需要标题和内容,还需要发布日期、评论等等。为每个相关的信息定义一个 prop 会变得很麻烦:
<blog-post
v-for="post in posts"
v-bind:key="post.id"
v-bind:title="post.title"
v-bind:content="post.content"
v-bind:publishedAt="post.publishedAt"
v-bind:comments="post.comments"
></blog-post>
所以是时候重构一下这个<blog-post> 组件
了,让它变成接受一个单独的 post prop:
记住一个组件默认可以拥有任意数量的 prop,任何值都可以传递给任何 prop。包括可以传递对象
<div id="app-5">
<blog-post
v-for="item in items"
v-bind:key="item.id"
v-bind:post="item.post" >
</blog-post>
</div>
<!--自定义组件模板-->
<template id="mytemplate">
<div>
<h3>{{ post.title }}</h3>
<div v-html="post.content"> </div>
</div>
</template>
Vue.component('blog-post',{
props:['post'],
template:"#mytemplate"
})
new Vue({
el:"#app-5",
data:{
items:[
{
id:1,
post:{title:"My journey with Vue",content:"这是xxxxMy journey with Vue"}
},
{
id:2,
post:{title:"Blogging with Vue",content:"这是xxxxBlogging with Vue"}
},
{
id:3,
post:{title:"Why Vue is so fun",content:"这是xxxxWhy Vue is so fun"}
}
]
}
})
4. 监听子组件事件
在我们开发<blog-post>
组件时,它的一些功能可能要求我们和父级组件进行沟通。例如我们可能会引入一个辅助功能来放大博文的字号,同时让页面的其它部分保持默认的字号。
在其父组件中,我们可以通过添加一个 postFontSize 数据属性来支持这个功能:
new Vue({
el: '#app-6',
data: {
posts: [/* ... */],
postFontSize: 1
}
})
它可以在模板中用来控制所有博文的字号:
<div id="blog-posts-events-demo">
<div :style="{ fontSize: postFontSize + 'em' }">
<blog-post
v-for="post in posts"
v-bind:key="post.id"
v-bind:post="post"
></blog-post>
</div>
</div>
现在我们在每篇博文正文之前添加一个按钮来放大字号:
Vue.component('blog-post', {
props: ['post'],
template: `
<div class="blog-post">
<h3>{{ post.title }}</h3>
<button>
Enlarge text
</button>
<div v-html="post.content"></div>
</div>
`
})
问题是这个按钮不会做任何事:
<button>
Enlarge text
</button>
当点击这个按钮时,我们需要告诉父级组件放大所有博文的文本。幸好 Vue 实例提供了一个自定义事件的系统来解决这个问题。父级组件可以像处理 native DOM 事件一样通过 v-on 监听子组件实例的任意事件:
<blog-post
...
v-on:enlarge-text="postFontSize += size"
></blog-post>
同时子组件可以通过调用内建的$emit 方法
并传入事件名称来触发一个事件:
<button v-on:click="$emit('enlarge-text',0.1)">
Enlarge text
</button>
$emit:触发当前实例上的事件。附加参数都会传给监听器回调。
不了解$emit
请查看官方api文档 https://cn.vuejs.org/v2/api/#vm-emit
有了这个 v-on:enlarge-text="postFontSize += 0.1" 监听器
,父级组件就会接收该事件并更新 postFontSize 的值。
上述完整代码:
<div id="app-5" v-bind:style="{ fontSize:postFontSize+'em'}" >
<blog-post
v-for="item in items"
:key="item.id"
:post="item.post"
v-on:enlarge-text="enlargeText">
<!--v-on:enlarge-text="postFontSize+=$event"-->
</blog-post>
</div>
<!--自定义组件模板-->
<template id="mytemplate">
<div class="blog-post">
<h3>{{ post.title }}</h3>
<div v-html="post.content"> </div>
<button v-on:click="$emit('enlarge-text',0.1)">放大字体</button>
</div>
</template>
Vue.component('blog-post',{
props:['post'],
template:"#mytemplate"
})
new Vue({
el:"#app-5",
data:{
items:[
{
id:1,
post:{title:"My journey with Vue",content:"这是xxxxMy journey with Vue"}
},
{
id:2,
post:{title:"Blogging with Vue",content:"这是xxxxBlogging with Vue"}
},
{
id:3,
post:{title:"Why Vue is so fun",content:"这是xxxxWhy Vue is so fun"}
}
],
postFontSize:1
},
methods:{
enlargeText:function(size){
this.postFontSize+=size
}
}
})
不理解的拆开来写,有助于理解!
4.1 在组件上使用v-model
自定义事件也可以用于创建支持v-model
的自定义输入组件。记住:
<input v-model="searchText">
等价于:
<input
v-bind:value="searchText"
v-on:input="searchText = $event.target.value"
>
当用在组件上时,v-model
则会这样:
<div id="app-7">
<custom-input-one v-model="searchText"></custom-input-two>
<p>文本框内容:{{searchText}}</p>
</div>
为了让它正常工作,这个组件内的<input>
必须:
- 将其
value
attribute 绑定到一个名叫value 的 prop 上
- 在其
input 事件
被触发时,将新的值通过自定义的 input 事件抛出
<template id="myinputOne">
<input v-bind:value="value" v-on:input="$emit('input',$event.target.value)" />
</template>
Vue.component("custom-input-one",{
props:['value'],
template:'#myinputOne'
})
new Vue({
el:"#app-7",
data:{
searchText:""
}
})
上面说v-model
等于v-bind:value="searchText"
v-on:input="searchText = $event.target.value"
因此还可以这样写
<div id="app-6">
<custom-input-two v-bind:value="searchText" v-on:input="inputEvent"></custom-input-two>
<p>文本框内容:{{searchText}}</p>
</div>
<template id="myinputTwo">
<input v-bind:value="value" v-on:input="$emit('input',$event.target.value)" />
</template>
Vue.component('custom-input-two',{
props:['value'],
template:'#myinputTwo'
})
new Vue({
el:"#app-6",
data:{
searchText:""
},
methods:{
inputEvent:function(value){
this.searchText=value
}
}
})
5. 通过插槽分发内容
和 HTML 元素一样,我们经常需要向子组件传递内容,像这样:
<div id="app-8">
<alert-box>Something bad happend</alert-box>
</div>
<template id="errorTemplate">
<div>
<strong>Error!</strong>
</div>
</template>
Vue.component("alert-box",{
template:'#errorTemplate'
})
new Vue({
el:"#app-8"
})
结果:
<alert-box>
中的文本没有渲染,因为我们没有将文本传递给子组件
幸好,Vue 自定义的 元素让这变得非常简单:
<template id="errorTemplate">
<div>
<strong>Error!</strong>
<slot></slot>
</div>
</template>
Vue.component("alert-box",{
template:'#errorTemplate'
})
结果:
6. 动态组件
有的时候,在不同组件之间进行动态切换是非常有用的,比如在一个多标签的界面里:
点击登陆时切换登陆组件;点击注册切换注册组件
<div id="app-9">
<a href="#" v-on:click.prevent="flag=true">登陆</a>
<a href="#" v-on:click.prevent="flag=false">注册</a>
<custom-login v-if="flag"></custom-login>
<custom-register v-else></custom-register>
</div>
Vue.component("custom-login",{
template:'<h3>登陆组件</h3>'
})
Vue.component("custom-register",{
template:'<h3>注册组件</h3>'
})
new Vue({
el:"#app-9",
data:{
flag:true
}
})
但是上面这种写法存在局限性,如果有三个乃至更多需要切换上面这种就不是很方便
因此Vue提供了<component> 元素加一个特殊的 is attribute 来实现:
<div id="app-10">
<a href="#" v-on:click.prevent="flag='custom-login'">登陆</a>
<a href="#" v-on:click.prevent="flag='custom-register'">注册</a>
<component v-bind:is="flag"></component>
</div>
Vue.component("custom-login",{
template:'<h3>登陆组件</h3>'
})
Vue.component("custom-register",{
template:'<h3>注册组件</h3>'
})
new Vue({
el:"#app-10",
data:{
flag:true
}
})
7. 解析DOM模板时的注意事项
有些 HTML 元素,诸如<ul>、<ol>、<table> 和 <select>,
对于哪些元素可以出现在其内部是有严格限制的。而有些元素,诸如<li>、<tr> 和 <option>
,只能出现在其它某些特定的元素内部。
<div id="app-11">
<table>
<custom-lable></custom-lable>
</table>
</div>
Vue.component('custom-lable',{
template:"<h3>自定义组件</h3>"
})
new Vue({
el:"#app-11"
})
渲染后的HTML:
可以发现本来应该出现在<table>
内部的<h3>
跑到外面去了。这样肯定不行的
幸好这个特殊的 is attribute 给了我们一个变通的办法:
<div id="app-11">
<table>
<tr is="custom-lable"></tr>
</table>
</div>
Vue.component('custom-lable',{
template:"<h3>自定义组件</h3>"
})
new Vue({
el:"#app-11"
})
效果:
需要注意的是如果我们从以下来源使用模板的话,这条限制是不存在的:
字符串 (例如:template: '...')
单文件组件 (.vue)
<script type="text/x-template">
字符串例子如下:
<div id="app-11">
<custom-lable-two></custom-lable-two>
</div>
Vue.component('custom-lable-one',{
template:"<h3>自定义组件字符串例子</h3>"
})
Vue.component('custom-lable-two',{
template:'<table><custom-lable-one></custom-lable-one></table>'
})
new Vue({
el:"#app-11"
})
效果:
单文件组件 (.vue) 需要使用 vue-cli 脚手架目前还没学习,不演示
<script type="text/x-template">例子如下:
<div id="app-11">
<custom-lable-three></custom-lable-three>
</div>
<script type="text/x-template" id="custom-lable-template">
<table><custom-lable-one></custom-lable-one></table>
</script>
Vue.component('custom-lable-one',{
template:"<h3>自定义组件text/x-template</h3>"
})
Vue.component('custom-lable-three',{
template:"#custom-lable-template"
})
new Vue({
el:"#app-11"
})
效果: