组件
组件初始化
Vue.component('button-counter', {
data: function () {
return {
count: 0
}
},
template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})
子组件传值
子组件中如何引用data中的属性
<blog-post
v-for="post in posts"
v-bind:key="post.id"
v-bind:post="post"
></blog-post>
Vue.component('blog-post', {
props: ['post'],
template: `
<div class="blog-post">
<h3>{{ post.title }}</h3>
<div v-html="post.content"></div>
</div>
`
})
> props定义在子组件中用到的属性,通过v-bind绑定data属性到子组件
子组件事件
//子组件事件
//子组件向上传递事件名称
<button v-on:click="$emit('enlarge-text')">
Enlarge text
</button>
//父组件监听
<blog-post
...
v-on:enlarge-text="postFontSize += 0.1"
></blog-post>
子组件向上传递参数
当在父级组件监听这个事件的时候,我们可以通过 $event 访问到被抛出的这个值
<button v-on:click="$emit('enlarge-text', 0.1)">
Enlarge text
</button>
<blog-post
...
v-on:enlarge-text="postFontSize += $event"
></blog-post>
或者,如果这个事件处理函数是一个方法:
<blog-post
...
v-on:enlarge-text="onEnlargeText"
></blog-post>
那么这个值将会作为第一个参数传入这个方法:
methods: {
onEnlargeText: function (enlargeAmount) {
this.postFontSize += enlargeAmount
}
}
组件上v-model的使用
组件上
v-model
的使用是借助v-bind
和v-on
的结合
<custom-input
v-bind:value="searchText"
v-on:input="searchText = $event"
></custom-input>
Vue.component('custom-input', {
props: ['value'],
template: `
<input
v-bind:value="value" //固定名
v-on:input="$emit('input', $event.target.value)"
>
`
})
<custom-input v-model="searchText"></custom-input>
插槽
<alert-box>
Something bad happened.//插入插槽的内容
</alert-box>
Vue.component('alert-box', {
template: `
<div class="demo-alert-box">
<strong>Error!</strong>
<slot></slot>
</div>
`
})
//定义alert-box组件,slot是vue提供的插槽