<div id="app" class="demo">
<post-list></post-list>
</div>
<script src="https://unpkg.com/vue@next"></script>
<script>
const app = Vue.createApp({});
const PostListItem = {
props: {
post: {
type: Object,
default: function() {
return {}
}
},
},
methods: {
handleClick() {
this.$emit("vote")
}
},
template: `
<div>
<h3>标题: {{ post.title }}</h3>
<p>作者: {{ post.author }} | 发表日期: {{ post.data }} | 点赞数: {{ post.vote }}</p>
<p><button @click="handleClick">点赞</button></p>
</div>
`
}
app.component('PostList', {
data() {
return {
posts: [
{id: 1, title: '《Servlet/JSP深入详解》怎么样', author: '张三', date: '2019-10-21 20:10:15', vote: 0},
{id: 2, title: '《VC++深入详解》观后感', author: '李四', date: '2019-10-10 09:15:11', vote: 0},
{id: 3, title: '《Java无难事》怎么样', author: '王五', date: '2020-11-11 15:22:03', vote: 0}
]
}
},
components: {
PostListItem
},
methods: {
handleVote(id) {
this.posts.map(item => {
item.id === id ? {...item, vote: ++item.vote} : item
})
}
},
template: `
<PostListItem
v-for = "post in posts"
:key="post.id"
:post="post"
@vote="handleVote(post.id)"/>
`
})
app.mount('#app')
</script>