Vue父子组件传值是个比较经典的问题,在这里,咱们先谈一下,子组件给父组件传值。
- 这是一个子组件
<!-- 子组件1 -->
<template>
<div class="list">
<ul>
<li v-for="item in list" :key="item.id">
{{ item.title }}
</li>
</ul>
</div>
</template>
<script>
export default {
props:{
list:Array
},
name: "items",
}
</script>
<style scoped>
</style>
这是列表子组件,它通过 this.$emit的方式给父组件传递了自己所绑定的title值。这样就向外触发了一个addGet事件。
<!-- 子组件2 -->
<template>
<div class="input">
<Input type="text" v-model="title" style="width: 100px"></Input>
<Button @click="add">添加</Button>
</div>
</template>
<script>
export default {
name: "input",
data(){
return{
title:''
}
},
methods:{
add(){
this.$emit('addGet',this.title);
}
}
}
</script>
<style scoped>
</style>
这是一个父组件
父组件在这里定义了一个自定义事件addGet,事件名是addInfo,用来接受子组件传过来的title值。
<!-- 父组件 -->
<template>
<div id="app">
<input @addGet="addInfo"></input>
<items :list="list"></items>
</div>
</template>
<script>
import Items from "./items ";
import Input from "./input ";
export default {
name: "test",
components: { Items , Input },
data() {
return {
list:[
{
id:1,
title:'标题1'
},
{
id:2,
title:'标题2'
}
]
}
},
methods: {
addInfo(title){
this.list.push({
id:Math.random(),
title
})
}
}
}
</script>
<style scoped>
</style>
这个时候你会看见父子组件是这样的:
此时你输入标题3,点击添加,就会在标题2的下边新增一个标题3啦
这是父子组件最后得到的效果图
今天就到这里了
以后还会继续更新。
版权声明:本文为qq_45222558原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。