vue如何在父组件中调用子组件的方法

 父组件
1
<template> 2 <div> 3 <child ref="mychild"></child> 4 <button @click="parentSetVal("这是新值")">点击</button> 5 </div> 6 </template> 7 <script> 8 import child from "./child" 9 exprot default(){ 10 components:{ 11 child 12 }, 13 methods:{ 14 parentSetVal(val){ 15 this.$refs.mychild.setVal(val) 16 } 17 } 18 } 19 </script>
 子组件
1
<template> 2 <div> 3 <p>{{val}}</p> 4 <button @click="setVal("这是值2")">点击</button> 5 </div> 6 </template> 7 <script> 8 exprot default(){ 9 data(){ 10 return { 11 val:"这是值1" 12 } 13 }, 14 methods:{ 15 setVal(val){ 16 this.val(val); 17 } 18 } 19 } 20 </script>

要点:
1.子组件需要已注册;
2.<child ref="myChild"></child>中mychild是子在父中的名字;
3.通过this.$refs.myChild.setVal()调用子组件的方法;

参考:https://www.cnblogs.com/gitByLegend/p/10868538.html

猜你喜欢

转载自www.cnblogs.com/yandeli/p/11884157.html