vue父子组件通信
一、父传子(数据)
父组件:
<template> <div> <children :msg="msg"/> </div> </template> import children from "子组件地址"; <script> components: { children }, data() { return { msg: '传给子', }; } </script>
子组件:
<template> <div> <span>{{msg}}<span> </div> </template> <script> props: { msg:{ type: String } }, </script>
二、父传子(函数)
父组件:
<template> <div> <children :fatherEvent="fatherEvent"/> </div> </template> import children from "子组件地址"; <script> components: { children }, methods: { fatherEvent() { alert("我是父组件方法") } } </script>
子组件:
<template> <div> <button @click="myfather">点我掉用父组件方法<button> </div> </template> <script> props: { fatherEvent: { type: Function, } }, methods: { myfather() { this.fatherEvent() } } </script>
三、子传父
子组件:
<template> <div> <button @click="myemit">点我发射方法<button> </div> </template> <script> methods: { myemit() { this.$emit('myemit',"发射给父组件") } } </script>
父组件:
<template> <div> <children @myemit="myemit"/> </div> </template> import children from "子组件地址"; <script> components: { children }, methods: { myemit(val) { console.log(val) } } </script>
四、父组件直接使用子组件方法
子组件:
<template> <div> <span>我是子组件<span> </div> </template> <script> methods: { childEvent(){ alert("我在子组件") } } </script>
父组件:
<template> <div> <children ref="childRef"/> <button @click="childClick">点我调用子组件的方法</button> </div> </template> import children from "子组件地址"; <script> components: { children }, methods: { childClick () { this.$refs.childRef.childEvent(); } } </script>
五、子组件直接使用父组件方法
父组件:
<template> <div> <children/> </div> </template> import children from "子组件地址"; <script> components: { children }, methods: { fatherEvent() { alert("我是父组件方法") } } </script>
子组件:
<template> <div> <button @click="myfather">点我掉用父组件方法<button> </div> </template> <script> methods: { myfather() { this.$parent.fatherEvent() } } </script>