組件案例-評論列表(涉及父子組件之間的通信)

JS代碼

主要業務邏輯寫在代碼註釋中

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title></title>
	<script type="text/javascript" src="js/vue.js"></script>
	<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
</head>
<body>
	<div id="app">
		<com-box @func="loadComments"></com-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="tmp1">
		<div>
			<div class="form-group">
				<label>評論人:</label>
				<input type="text" calss="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="postComment">
			</div>
		</div>
	</template>

	<script>
		var comBox = {
			data(){
				return {
					user:'',
					content:''
				}
			},
			methods:{
				postComment(){//發表評論的方法
					//分析:發表評論的業務邏輯
					//1.評論數據存到哪裏去?   存放到了localStorage中 localStorage.setItem('','')
					//2.先組織出一個最新的評論數據對象
					//3.想辦法把第二步得到的評論對象保存到localStorage中
					// 3.1localStorage只支持存放字符串數據,要先調用JSON.Stringify
					// 3.2在保存最新的評論數據之前,要先從localStorage獲取到之前的評論數據(String),轉換爲一個數組對象,然後把最新的評論push到這個數組中
					// 3.3如果獲取到的localStorage中的評論字符串爲空或者不存在,則可以返回一個'[]'讓JSON.parse去轉換
					// 3.4把最新的評論列表數組,再次調用JSON.stingify轉換爲數組字符串,然後
					// 調用localStorage.setItem()
					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')

				}
			},
			template:'#tmp1'
		}

		var vm = new Vue({
			el:'#app',
			data:{
				list:[
					{id:Date.now()+'1',user:'yuyan',content:'力拔山河氣蓋世'},
					{id:Date.now()+'2',user:'anqi',content:'城裏頭的人脾氣大得黑死人'},
					{id:Date.now()+'3',user:'wnz',content:'giao'}
				]
			},
			created(){
				this.loadComments()
			},
			methods:{
				loadComments(){//從本地的localStorage中加載評論列表
					var list = JSON.parse(localStorage.getItem('cmts') || '[]')
					this.list = list
				}
			},
			components:{
				'com-box':comBox
			}
		});
	</script>	
</body>
</html>

效果展示
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章