<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./bootstrap.css">
<title>Document</title>
</head>
<style>
#app {
width: 700px;
margin: 0 auto;
}
</style>
<body>
<div id="app">
<msg-title></msg-title>
</div>
</body>
<script src="../vue.js"></script>
<script src="../axios.js"></script>
<script>
//创建标题组件
const msgTitle = {
template: `
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">留言板</h3>
</div>
<msg-input></msg-input>
</div>
`
}
//创建输入框组件
const msgInput = {
template: `
<div class="panel-body">
<input type="text" class="form-control" placeholder="请输入姓名" v-model="addContents.user">
<br>
<textarea class="form-control" rows="5" placeholder="请输入留言内容" v-model="addContents.content"></textarea>
<br>
<button type="button" class="btn btn-primary pull-right" @click="submit">提交</button>
<br/><br/>
<msg-list :contents="contents"></msg-list>
<!--:contents="contents"把content这个动态的数据传送给子组件-->
</div>
`,
data() {
return {
addContents:
{
user: "",
content: ""
}
,
contents: []
}
},
methods: {
submit() {
this.contents.unshift(Object.assign({}, this.addContents));
this.addContents.content = '';
}
}
}
//创建留言列表组件
const msgList = {
template: `
<ul class="list-group">
<template v-if="contents.length">
<li class="list-group-item" v-for="(childContent,index) in childContents">
<button @click="del(index)" type="button" class="close" aria-label="Close"><span
aria-hidden="true">×</span></button>
<h5 class="list-group-item-heading" style="font-weight:700">{{childContent.user}}:</h5>
<p class="list-group-item-text">{{childContent.content}}</p>
</li>
</template>
<li class="list-group-item" v-else>
<h5 class="list-group-item-heading" style="font-weight:700">暂无留言</h5>
</li>
</ul>
`,
props: ["contents"],//自组件中用props接收数据,但是子组件无法修改这个数据
data(){
return{
childContents:this.contents//所以子组件把这个数据拷贝一份留给自己进行操作
}
},
methods:{
del(index){
this.childContents.splice(index,1)
}
}
}
//注册组件
Vue.component("msgTitle", msgTitle);
Vue.component("msgInput", msgInput);
Vue.component("msgList", msgList);
const app = new Vue({
el: "#app",
})
</script>
</html>