vue 父子组件中的通信

父组件

<div><child @upup="change" :child-msg="data">

<div slot="slot1">父组件插入</div>

<child></div>

<div>{{childData}}</div>

export default {

components: {

child

},

data () {

return {

data: "from parent",

childData:""

}

},

methods:{

change(msg){

this.childData=msg;

this.data="parent change"

}

}

}

子组件

<li>{{msg}}</li>

<li><slot name="slot1">子组件<slot></li>

<li>{{childMsg}}<li>

<li><div@click="toParent">click To parent</div><li>

export default {

name:"child",

components: {

},

data () {

return {

msg: 'this is child',

data:"from child"

}

},

props:{

childMsg: {

type: String,

default: "null" //这样可以指定默认的值

}

},

methods:{

toParent(){

this.$emit('upup',this.data); //主动触发upup方法,'hehe'为向父组件传递的数据

}

}

}

子组件通过props来接收数据:

name:"child",

components: {

},

data () {

return {

msg: 'this is child',

data:"from child"

}

},

props:{

childMsg: {

type: String,

default: "null" //这样可以指定默认的值

}

},

methods:{

toParent(){

this.$emit('upup',this.data); //主动触发upup方法,'hehe'为向父组件传递的数据

}

}

}

父组件向子组件传值,子组件用props接受,data改变后,子组件内childMsg也改变

子组件向父组件传值,用事件,父组件接受事件要加在子组件上

顺便用了slot当子组件模板只有slot 时,父组件内容片段将插入到 slot 所在的 DOM 位置,并替换掉 slot 标签本身。

点击前


点击后

查看上述代码

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容