<body>
<script src="../libs/vue.js"></script>
<div id="app">
<com2
@add="addItem"></com2>
<!--父组件往子组件数据传递-->
<com1
:array="lists"
@delete="deleteIndex"></com1>
</div>
<template id="temp">
<div>
<div v-for="(item,index) in array" :key="index">
<span class="title" @click="deleteItem(index)">{{item.title}}</span>
<br>
<span class="desc">{{item.desc}}</span>
<div class="line"></div>
</div>
</div>
</template>
<template id="temp2">
<div>
<input type="text" v-model="title">
<input type="text" v-model="desc">
<button style="width: 80px; height: 30px" @click="submit">提交</button>
</div>
</template>
<script>
/*全局组件,用来显示数组里的数据*/
Vue.component('com1', {
template: '#temp',
props: {
/*用于接收父组件传来的数据*/
array: Array,
},
methods: {
deleteItem(index) {
//点击标题删除item
this.$emit('delete', index)
}
}
})
/*全局组件,用来显示输入的key和value*/
Vue.component('com2', {
template: '#temp2',
data() {
return {
title: '',
desc: ''
}
},
methods: {
submit() {
//提交按钮的事件
var data = {
title: this.title,
desc: this.desc
}
//子组件往父组件发送数据
this.$emit('add', data)
}
}
})
var app = new Vue({
el: '#app',
data: {
message: '',
lists: [
{
title: '这是标题1',
desc: '这是描述1'
},
{
title: '这是标题2',
desc: '这是描述2'
},
{
title: '这是标题3',
desc: '这是描述3'
},
{
title: '这是标题4',
desc: '这是描述4'
},
{
title: '这是标题5',
desc: '这是描述5'
},
]
},
methods: {
addItem(data) {
//data { title: this.title, desc: this.desc}
this.lists.push(data)
},
deleteIndex(index) {
//删除数据
this.lists.splice(index, 1)
}
}
})
</script>
<style>
.title {
font-size: 20px;
color: red;
}
.desc {
font-size: 14px;
color: black;
}
.line {
width: 100%;
height: 1px;
margin-top: 10px;
background: #999999;
}
input {
height: 30px;
}
</style>
网友评论