1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > Vue组件间通信:父传子(props) 子传父($emit)

Vue组件间通信:父传子(props) 子传父($emit)

时间:2020-10-31 17:07:21

相关推荐

Vue组件间通信:父传子(props) 子传父($emit)

父子组件的关系可以总结为 prop 向下传递,emit事件向上传递。父组件通过prop给子组件下发数据,子组件通过事件emit事件向上传递。 父组件通过 prop 给子组件下发数据,子组件通过事件emit事件向上传递。父组件通过prop给子组件下发数据,子组件通过事件emit给父组件发送消息.

一、父组件向子组件传参:

看代码:

父组件

<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中定义一个按钮:

<button @click=“sendTOParent”>向父组件传值,

2)在methods中:

sendTOParent(){

this.$emit(‘listenToChildEvent’,this.data)

}

istenToChildEvent函数

this.data是要参数;

3. 父组件中:

4. 在tempalte中接受:

1),

2)methods中:

showMsgfromChild(data){

console.log(data)

}

文字版解释:

子组件中需要以某种方式例如点击事件的方法来触发一个自定义事件

将需要传的值作为$emit的第二个参数,该值将作为实参传给响应自定义事件的方法

在父组件中注册子组件并在子组件标签上绑定对自定义事件的监听

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。