父组件
<template>
<div
id="app"
style="border:solid 2px black"
>
<div id="nav">
<router-link to="/home">进入主页</router-link>
<div>
<h1>我是TodoList5的父组件</h1>
<input
v-model="inputValue"
type="text"
/>
<button @click="addDataToList">添加</button>
<!-- 组件化触发原生事件,子组件通过 @click.native 给最外层的 DOM 元素绑定事件,利用 $event 获取索引。本质上这利用了 BOM 的事件委托机制 -->
<list-item
:list="list"
@click.native="delDataFromList($event)"
></list-item>
</div>
</div>
<router-view />
</div>
</template>
<script>
import ListItem from './TodoList5'
/**
*1. 父组件引入子组件,父组件修改变量值
*/
export default {
name: 'Welcome',
data() {
return {
list: [],
inputValue: ''
}
},
components: {
ListItem
},
created() {
},
mounted() {},
methods: {
addDataToList() {
if (this.inputValue.length === 0) {
return '长度为0不添加'
}
this.list.push(this.inputValue)
this.inputValue
},
delDataFromList(event) {
/**
* event.target.propertyName和event.target.getAttribute("propertyName")区别
*本句话转载:https://blog.csdn.net/qq_36824782/article/details/78350092
* getAttribute拿的是html属性的值,而prop是DOM接口,
* 存取如何是由DOM规范定义的,跟html上的值是不一定对应的。
* 比如 input.value 你可以改变,但是 input.getAttribute('value') 你拿到的总是html上的属性的值,
* 是不变的。再如 a.href 得到总是绝对地址,而 a.getAttribute('value') 则是 html上写的地址,原来是什么就是什么。
*/
let index = event.target.getAttribute('data-key')
this.list.splice(index, 1)
}
},
computed: {}
}
</script>
<style scoped lang="scss"></style>
子组件
<template>
<div style="border:solid 2px blue">
<h1>我是TodoList5组件</h1>
<div v-for="(item, index) in list" @click="delDataFromList(index)" :key="index">{{ item }}</div>
</div>
</template>
<script>
export default {
name: 'List',
data() {
return {}
},
props: {
list: {
type: Array,
default() {
return []
}
}
},
components: {},
created() {},
mounted() {},
methods: {},
computed: {}
}
</script>
<style scoped lang="scss"></style>