一、使用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/n/333398.html
微信扫一扫
支付宝扫一扫