父組件
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()調用子組件的方法;