1、在父组件中使用子组件内的方法
//父组件代码 <template> <div> <el-button @click="click">点击调用子组件中的函数</el-button> <Son ref="son" /> </div> </template> <script> import Son from "./son"; export default { name: "father", data() { return {}; }, components:{ Son //记得注册组件,不然无法读取子组件中的内容 }, methods: { click() { this.$refs.son.textShow(); } } }; </script> <style> </style>
//子组件代码 <template> <div> <p v-if="!!show">我的方法被父组件调用了</p> </div> </template> <script> export default { name:'Son', data(){ return{ show:false } }, methods:{ textShow(){ this.show=!this.show } } } </script> <style> </style>
由于子组件中show为false 一开始并不会显示子组件中的内容
点击按钮
这便实现了在父组件中调用子组件的方法。
2、父子组件间数据的传递
1、父组件给子组件传递数据
//父组件
<template> <div> <el-button @click="click">点击调用子组件中的函数</el-button> <Son ref="son" :fatherData='outputVal'/>//绑定需要传递的数据 </div> </template> <script> import Son from "./son"; export default { name: "father", data() { return { outputVal:'这是父组件传递给子组件的数据' //增加代码 }; }, components:{ Son }, methods: { click() { this.$refs.son.textShow(); } } }; </script> <style> </style>
//子组件
<template> <div> <p v-if="!!show">我的方法被父组件调用了</p> <p>{{fatherData}}</p>//输出父组件传过来的数据 </div> </template> <script> export default { name:'Son', data(){ return{ show:false } }, props:{ //使用props声明要接收的值 fatherData:{
type:String ,//定义接收数据的类型若类型不符合将会在控制台输出错误
default:''//定义默认值,当父组件没有传递数据时,会使用默认值
} }, methods:{ textShow(){ this.show=!this.show } } } </script> <style> </style>
若将fatherData的类型改为Number,控制台会输出错误
2、*子组件向父组件传递数据
//父组件
<template> <div> <p>{{initVal}}</p> <Son ref="son" :fatherData='outputVal' @ouput='getSonVal'/> </div> </template> <script> import Son from "./son"; export default { name: "father", data() { return { initVal:'这是父组件自身的值' }; }, components:{ Son }, methods: { getSonVal(val){ this.initVal=val } } }; </script> <style> </style>
//子组件 <template> <div> <el-button @click="ouputToFather">子组件中的按钮</el-button> </div> </template> <script> export default { name: "Son", data() { return { outSonVal:'我是子组件传递给父组件的数据' }; }, methods: { ouputToFather(){ this.$emit('ouput',this.outSonVal)//分发名为output的事件,将outSonVal的值发送出去 } } }; </script> <style> </style>
点击按钮
我个人对$emit的理解:当我们点击按钮,子组件便会分发一个名为output的事件,父组件中使用函数接收该事件传递的数据。