组件数据传递:
- 父组件向内传递属性---动态属性
- 子组件向外发布事件
- solt 插槽传递模板---具名solt
1. 父组件向子组件传递数据
子组件在父组件的并作为标签引入,通过设置标签的属性传递数据,在子组件用props接受,,例如下面这样,父组件parent.vue引入子组件child.vue,将父组件的数据name通过设置标签child的name属性传递给子组件,子组件通过props传递接受,接受后,在子组件内this.name就是父组件的name数据。
父组件:
<template>
<div>
<child :name="name"></child>
</div>
</template>
<script>
import child from "./child"
export default {
name: "list",
components: {child},
data(){
return {
name:"hello",
}
}
}
</script>
<style scoped>
</style>
子组件:
<template>
<div>{{name}}</div>
</template>
<script>
export default {
name: "edit",
props: {
name :String
}
}
</script>
<style scoped>
</style>
2. 子组件向父组件传递数据
1.发布订阅 发布 emit 订阅 on{}
2.on订阅,emit发布,on和emit是在Vue的原型上的,每个实例都可以调用。
3.父亲绑定一个事件,儿子触发这个事件,并将参数传递过去
子组件:
<template>
<div style="margin-top: 300px;margin-left: 500px;">
<input type="text" v-model="book"/>
<button @click="add">添加</button>
<p v-for="(item, index) of books" :key="index">{{item}}</p>
</div>
</template>
<script>
export default {
name:'child',
props:{
books:Array
},
data() {
return {
book:""
}
},
methods: {
add(){
this.$emit('update',this.book);
}
}
}
</script>
<style>
</style>
父组件:
<template>
<div>
<span>hello</span>
<child ref="child" :books="books" @update="addBook"></child>
</div>
</template>
<script>
import child from './child';
export default {
components:{child},
data: function () {
return {
books:[]
}
},
methods: {
addBook(data){
this.books.push(data);
}
}
}
</script>
<style>
</style>
来源:https://www.cnblogs.com/shix0909/p/11213733.html