要引入的文件
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<link rel="stylesheet" href="./bootstrap/css/bootstrap.min.css">
静态部分
<div id='app'>
<div class="container">
<son @getlist="getlist"></son>
<ul class="list-group">
<li class="list-group-item" v-for="(item,index) in list" :key="index">
{{item.content}}
<span class="badge">评论人:{{item.name}}</span>
</li>
</ul>
</div>
</div>
组件
<template id="son">
<div>
<div class="form-group">
<label class="" for="">评论人</label>
<input type="text" class="form-control" id="" placeholder="Input field" v-model="name">
</div>
<div class="form-group">
<label class="" for="">评论内容</label>
<input type="text" class="form-control" id="" placeholder="Input field" v-model="content">
</div>
<button type="button" class="btn btn-info" @click="comment">发表评论</button>
</div>
</template>
vue实例部分
Vue.component('son', {
template: '#son',
data() {
return {
name: '',
content: ''
}
},
methods: {
comment() {
var obj = {
name: this.name,
content: this.content
}
this.$emit('getlist', obj)
this.name = ''
this.content = ''
}
}
})
const vm = new Vue({
el: '#app',
data: {
list: [],
},
created() {
console.log(localStorage);
if (this.list !== '') {
this.list = JSON.parse(localStorage.getItem('list'))
}
},
methods: {
getlist(data) {
this.list.push(data)
localStorage.setItem('list', JSON.stringify(this.list))
}
}
})