一、使用this.$refs調用子組件方法
在Uniapp中,如果我們想要調用單個子組件的方法,可以通過this.$refs來實現。我們可以在子組件中加入ref屬性來指定子組件的名稱,然後在父組件中使用this.$refs來獲取到該子組件的實例,從而調用該子組件的方法。
示例代碼如下:
// 子組件 <template> <div> <button @click="childSayHello">子組件方法調用</button> </div> </template> <script> export default { methods: { childSayHello() { console.log("Hello from child component!"); } } } </script> // 父組件 <template> <div> <child-component ref="child"></child-component> <button @click="callChildMethod">調用子組件方法</button> </div> </template> <script> import ChildComponent from "@/components/ChildComponent.vue"; export default { components: { ChildComponent }, methods: { callChildMethod() { this.$refs.child.childSayHello(); } } } </script>
在上面的代碼中,我們在子組件中定義了一個childSayHello方法,在父組件中引入了該子組件,並給它加上了ref屬性。在父組件的method中,我們通過this.$refs.child來獲取到這個子組件的實例,然後就可以調用該子組件的childSayHello方法了。
二、調用多個子組件的方法
有時候我們需要調用多個子組件的方法,此時我們可以使用數組的方式來存儲多個子組件的實例。示例代碼如下:
// 子組件1 <template> <div> <button @click="child1SayHello">子組件1方法調用</button> </div> </template> <script> export default { methods: { child1SayHello() { console.log("Hello from Child Component 1!"); } } } </script> // 子組件2 <template> <div> <button @click="child2SayHello">子組件2方法調用</button> </div> </template> <script> export default { methods: { child2SayHello() { console.log("Hello from Child Component 2!"); } } } </script> // 父組件 <template> <div> <child-component1 ref="child1"></child-component1> <child-component2 ref="child2"></child-component2> <button @click="callMultipleChildMethods">調用多個子組件方法</button> </div> </template> <script> import ChildComponent1 from "@/components/ChildComponent1.vue"; import ChildComponent2 from "@/components/ChildComponent2.vue"; export default { components: { ChildComponent1, ChildComponent2 }, methods: { callMultipleChildMethods() { const child1 = this.$refs.child1; const child2 = this.$refs.child2; child1.child1SayHello(); child2.child2SayHello(); } } } </script>
在上面的代碼中,我們定義了兩個子組件和一個父組件,分別通過ref屬性來指定子組件的實例名稱。在父組件中的method中,我們先獲取到這兩個子組件的實例,然後依次調用他們的child1SayHello和child2SayHello方法。
三、給子組件設置ref屬性
有時候我們想要動態設置子組件的名稱,此時我們需要為子組件設置ref屬性。可以通過v-bind:ref動態綁定ref屬性。示例代碼如下:
// 子組件 <template> <div> <button @click="childSayHello">子組件方法調用</button> </div> </template> <script> export default { methods: { childSayHello() { console.log("Hello from child component!"); } } } </script> // 父組件 <template> <div> <child-component v-bind:ref="childName"></child-component> <button @click="callChildMethod">調用子組件方法</button> </div> </template> <script> import ChildComponent from "@/components/ChildComponent.vue"; export default { components: { ChildComponent }, data() { return { childName: "child1" } }, methods: { callChildMethod() { this.$refs.child1.childSayHello(); } } } </script>
在上面的代碼中,我們在父組件的data中定義了一個childName變數,並將其綁定到子組件的ref屬性上。在父組件的method中,我們直接通過this.$refs.child1來獲取到這個子組件實例,並調用其方法,這裡的child1就是我們動態綁定的ref屬性的值。
原創文章,作者:EUGUJ,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/333398.html