数据通信
数据通信
监听子组件事件
在我们开发
new Vue({
el: "#blog-posts-events-demo",
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>
`,
});
当点击这个按钮时,我们需要告诉父级组件放大所有博文的文本。幸好
<blog-post ... v-on:enlarge-text="postFontSize += 0.1"></blog-post>
同时子组件可以通过调用内建的
<button v-on:click="$emit('enlarge-text')">Enlarge text</button>
有了这个
使用事件抛出一个值
有的时候用一个事件来抛出一个特定的值是非常有用的。例如我们可能想让
<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
自定义事件也可以用于创建支持
<input v-model="searchText" />
等价于:
<input
v-bind:value="searchText"
v-on:input="searchText = $event.target.value"
/>
当用在组件上时,
<custom-input
v-bind:value="searchText"
v-on:input="searchText = $event"
></custom-input>
为了让它正常工作,这个组件内的 必须:
- 将其
value
attribute 绑定到一个名叫value
的prop 上 - 在其
input
事件被触发时,将新的值通过自定义的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>
Links
- https://mp.weixin.qq.com/s/JLgASmwS7QI6h-ZBPlMBkw
Vue 组件数据通信方案总结