props 的传值
如有BlogPost.vue:
<script>
export default {
props: ['title']
}
</script>
<template>
<h4>{{ title }}</h4>
</template>
父文件:
<BlogPost title="My journey with Vue" />
父组件有一个数组:
export default {
// ...
data() {
return {
posts: [
{ id: 1, title: 'My journey with Vue' },
{ id: 2, title: 'Blogging with Vue' },
{ id: 3, title: 'Why Vue is so fun' }
]
}
}
}
使用:
<BlogPost
v-for="post in posts"
:key="post.id"
:title="post.title"
/>
监听事件
父组件中:
data() {
return {
posts: [
/* ... */
],
postFontSize: 1
}
}
<div :style="{ fontSize: postFontSize + 'em' }">
<BlogPost
v-for="post in posts"
:key="post.id"
:title="post.title"
@enlarge-text="postFontSize += 0.1"
/>
</div>
子组件BlogPost.vue中:
<template>
<div class="blog-post">
<h4>{{ title }}</h4>
<button @click="$emit('enlarge-text')">Enlarge text</button>
</div>
</template>
<script>
export default {
props: ['title'],
emits: ['enlarge-text']
}
</script>