"
"
0
一、父组件向子组件传值举例:
父组件
<template>
<div>
<h1>我是父组件</h1>
<!-- :title名称与子组件prop中的名称一致
=”title“ 与父组件中data数据中的title名称一致 -->
<children :title="title" :contents="content"></children>
</div>
</template>>
<script>
import Children from "./Children";
export default {
data() {
return {
title: "我是父组件的标题",
content: "我是内容"
};
},
components: {
Children
}
};
</script>
子组件:
<template>
<div>
<h1>children</h1>
<span>{ {title}}</span>
<br />
<span>{ {contents}}</span>
</div>
</template>>
<script>
export default {
props: {
title: String,
contents: String
}
};
</script>>
父组件向子组件传值
总结一下:
- 父组件中引入子组件、注册子组件,tempalte中使用子组件; import 、components、
- 子组件: props中创建一个属性,接受父组件传的值;
在template中使用 {{contents}}; - 父组件中的 , :title与子组件中prop添加的属性名称要一致;
=”title“与父组件中data数据中的title名称要一致;
注意:
props的值的写法:
props: {
title: String,
}
props: {
title: {
type: String, // [String, Number],
default: 1
}
}
二、 子组件向父组件传值
1.在子组件中创建一个按钮,给按钮绑定一个点击事件
2.在响应该点击事件的函数中使用$emit来触发一个自定义事件,并传递一个参数
子组件:
<template>
<div>
<h1>children</h1>
<button @click="sendTOParent">向父组件传值</button>
</div>
</template>>
<script>
export default {
data() {
return {
data: "子组件中的信息"
};
},
methods:{
sendTOParent(){
this.$emit('listenToChildEvent',this.data)
}
}
};
</script>>
3.在父组件中的子标签中监听该自定义事件并添加一个响应该事件的处理方法。
父子间代码
<template>
<div>
<h1>我是父组件</h1>
<children v-on:listenToChildEvent = 'showMsgfromChild'></children>
</div>
</template>>
<script>
import Children from "./Children";
export default {
data() {
return {
};
},
methods:{
showMsgfromChild(data){
console.log(data)
}
},
components: {
Children
},
};
</script>
子组件向父组件传值总结:
1.父组件: 引入子组件,住处,在tempalte中使用;
import 、components、
2. 子组件:
1)在template中定义一个按钮:
文字版解释:
子组件中需要以某种方式例如点击事件的方法来触发一个自定义事件
将需要传的值作为$emit的第二个参数,该值将作为实参传给响应自定义事件的方法
在父组件中注册子组件并在子组件标签上绑定对自定义事件的监听