vue中父子組件通信在日常開發中還是比較常用的,與之相關的文章也非常多,這次分享給大家的是一個子組件和父組件交互的小例子,效果如下
上半部分是評論列表,下半部分是子組件,當填寫評論人和評論內容,點擊發表刷新上半部分的評論列表
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>發佈評論</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
</style>
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
<div class="container" id="app">
<div class="row">
<ul class="list-group" style="margin-top:20px;">
<li class="list-group-item" v-for="item in commentList">
{{item.content}}
<span class="badge"> {{item.userName}}</span>
</li>
</ul>
<reply-form @func="refreshCommentList"></reply-form>
</div>
</div>
<template id="repForm">
<div>
<div class="form-group">
<label>評論人</label>
<input type="text" class="form-control" id="userName" v-model="userName"/>
</div>
<div class="form-group">
<label>評論內容</label>
<textarea name="" id="input" class="form-control" rows="5" v-model="content"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" @click.prevent="saveComment">發表</button>
</div>
</div>
</template>
<script>
var vm=new Vue({
el:"#app",
data:{
commentList:[]
},
methods:{
refreshCommentList:function refreshCommentList(){
console.log("-------");
var list=JSON.parse(localStorage.getItem('commentList')||'[]');
this.commentList=list;
}
},
created() {
this.refreshCommentList();
},
components:{
"reply-form":{
template:'#repForm',
data:function(){
return {
userName:'',
content:''
}
},
methods:{
saveComment:function saveComment(){
var comment={id:new Date(),userName:this.userName,content:this.content};
//取得之前存儲的元數據
var list=JSON.parse(localStorage.getItem('commentList')||'[]');
list.unshift(comment);
//重設localStorage
localStorage.setItem('commentList',JSON.stringify(list));
this.userName=this.content='';
//調用父組件方法刷新列表
this.$emit('func');
}
}
}
}
});
</script>
</body>
</html>
本例子的重點在於數據的存儲和子組件調用父組件的方法刷新列表,這裏使用瀏覽器的本地存儲localstorage,父組件的方法調用使用$emit