vue——33-父子元件傳方法(發表評論) 及 localStorage 的應用
阿新 • • 發佈:2018-12-15
引入檔案:bootstrap.css
html
<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.name}}</span>
{{item.content}}
</ li>
</ul>
</div>
<template id="tmp1">
<div>
<div class="form-group">
<label for="user">評論人:</label>
<input type="text" id="user" class="form-control" v-model="name">
</div>
<div class="form-group" >
<label for="connect">評論內容:</label>
<input type="text" id="connect" class="form-control" v-model="content">
</div>
<div class="form-group">
<input type="button" class="btn btn-primary" value="發表評論" @click="postComment" >
</div>
</div>
</template>
js
let commentBox = {
template: '#tmp1',
data() {
return {
name: '',
content: ''
}
},
methods: {
postComment() {
//發表評論的方法
// 1.評論存放進 localStorage 中 localStorage.setItem('','')
// 2.先組織出一個最新的評論資料物件
// 3.想辦法,把第二步中,得到的評論物件,儲存到 localStorage 中;
// 3.1.localStorage 只支援存放字串資料,要先呼叫 JSON.stringify
// 3.2.在儲存最新的評論資料之前,要先從 localStorage 獲取到之前的評論數
// 據(string),轉換為一個數組物件,然後,把最新的評論,push 到這個陣列
// 3.3.如果獲取到的 localStorage 中的評論字串,為空不存在,
// 則可以返回一個 '[]' 讓 JSON.parse 去轉換
// 3.4.把最新的評論列表組,再次呼叫 JSON.stringify 轉為陣列字串,
// 然後呼叫 localStorage.setItem()
let comment = {id: Date.now(), name: this.name, content: this.content};
// 從 localStorage 中獲取所有的評論
let list = JSON.parse(localStorage.getItem('cmts') || '[]');
list.unshift(comment);
// 重新儲存最新的評論資料
localStorage.setItem('cmts', JSON.stringify(list));
this.name = this.content = '';
this.$emit('func');//觸發這個事件
}
}
};
let vm = new Vue({
el: '#app',
data: {
list: []
},
methods: {
loadComments() {
//從本地的 localStorage 中,載入評論列表
this.list = JSON.parse(localStorage.getItem('cmts') || '[]');
}
},
components: {
cmtBox: commentBox
},
created() {
this.loadComments();
},
});