本文实例为大家分享了Vue组件实现评论区的具体代码,供大家参考,具体内容如下
实现代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, inital-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>评论</title>
<script src="vue.js"></script>
<link rel="stylesheet" href="bootstrap.min.css" >
</head>
<body>
<div id="app">
<cmt-box @func="loadComments"></cmt-box>
<ul class="list-group">
<li class="list-group-item" v-for="item in list" :key="item.id">
<span class="badge">评论人:{{ item.user }}</span>
{{ item.content }}
</li>
</ul>
</div>
<template id="tmpl">
<div>
<div class="form-group">
<label>评论人:</label>
<input type="text" class="form-control" v-model="user">
</div>
<div class="form-group">
<label>评论内容:</label>
<textarea class="form-control" v-model="content"></textarea>
</div>
<div class="form-group">
<input type="button" value="发表评论" class="btn btn-primary" @click="postComments">
</div>
</div>
</template>
<script>
var commentBox = {
template: '#tmpl',
data() {
return {
user: '',
content: ''
}
},
methods: {
postComments() {
var comment = {id: Date.now(), user:this.user, content:this.content }
var list = JSON.parse(localStorage.getItem('cmts') || '[]')
list.unshift(comment)
localStorage.setItem('cmts',JSON.stringify(list))
this.user = this.content = ''
this.$emit('func')
}
}
}
var vm = new Vue({
el: '#app',
data: {
list:[
{ time: Date.now(), user: '路人甲', content: '武汉加油' },
{ time: Date.now(), user: '炮灰乙', content: '中国加油' },
{ time: Date.now(), user: '小兵丙', content: '广东加油' },
{ time: Date.now(), user: '土匪丁', content: '全球加油' }
]
},
created(){
this.loadComments()
},
methods: {
loadComments(){
var list = JSON.parse(localStorage.getItem('cmts') || '[]')
this.list = list
}
},
components: {
'cmt-box': commentBox
}
});
</script>
</body>
</html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。