Vue父子组件间传值 之 $parent/$children 亦凉 2022-12-22 11:29 72阅读 0赞 ## 示例一:父组件向子组件传值 ## * 父组件: <template> <div> <h1>父组件</h1> <h-child></h-child> </div> </template> <script> // 引入子组件 import HChild from './Child' export default { name: 'Parent', components: { HChild }, data () { return { msg: 'data from parent' } }, methods: { fun () { console.log('parent fun') } } } </script> * 子组件: <template> <div> <h1>子组件</h1> <button @click="showParent">调用父组件的数据和方法</button> </div> </template> <script> export default { name: 'Child', methods: { showParent () { // 获取到所有的子组件 console.log(this.$parent) // 获取指定子组件中的指定数据 console.log(this.$parent.msg) // 调用子组件的方法 this.$parent.fun() } } } </script> 注意:在钩子方法mounted中无法获取到父组件中的数据和方法 结果: ![在这里插入图片描述][2020112012510286.png_pic_center] ## 示例二:子组件向父组件传值 ## * 子组件: <template> <div> <h1>子组件</h1> </div> </template> <script> export default { name: 'Child', data () { return { msg: 'msg from child' } }, methods: { fun () { console.log('child fun') } } } </script> * 父组件: <template> <div> <h1>父组件</h1> <h-child></h-child> </div> </template> <script> // 引入子组件 import HChild from './Child' export default { name: 'Parent', components: { HChild }, mounted () { // 获取到所有的子组件,结果是一个数组 console.log(this.$children) // 获取指定子组件中的指定数据 console.log(this.$children[0].msg) // 调用子组件的方法 this.$children[0].fun() } } </script> [2020112012510286.png_pic_center]: /images/20221120/6fdb3172bc184087bf13dec3516e4a79.png
还没有评论,来说两句吧...