一、Vue 3 调用子组件方法 child
在 Vue 3 中,为了更好的拆分组件,允许我们定义一个子组件,并且可以通过组件标签的方式去使用它。在像这种组件中,子组件方法调用就显得很重要。在这种情况下,可以使用 $refs 属性来选择子组件,并且调用其方法。
const ChildComponent = {
methods: {
hello() {
console.log('Hello from ChildComponent!');
}
}
}
export default {
components: { ChildComponent },
methods: {
callChildMethod() {
this.$refs.child.hello();
}
}
}
二、Vue 3 调用子组件函数
在 Vue 3 中,函数不再作为组件的方法存在。新的组件函数实际上作为子组件子组件实例的属性,可以通过访问该属性名来调用子组件函数。
const ChildComponent = {
setup() {
const sayHello = () => {
console.log('Hello from ChildComponent Function!');
}
return { sayHello };
}
}
export default {
components: { ChildComponent },
methods: {
callChildFunction() {
this.$refs.child.sayHello();
}
}
}
三、Vue 3 父组件调用子组件方法
有时我们需要在父组件中去调用子组件方法。Vue 3 给我们提供了可用性 API ,即 provide 和 inject。在父组件中,通过 provide 向下传递数据或者方法,在子组件中通过 inject 可以获取到数据或者方法。
const ChildComponent = {
setup(props, { expose }){
const sayHello = () => {
console.log('Hello from ChildComponent Function!');
}
expose({ sayHello })
// or
return { sayHello };
}
}
const ParentComponent = {
components: { ChildComponent },
methods: {
callChildMethod() {
this.$refs.child.sayHello();
}
},
setup() {
return { sayHello: inject('sayHello') }
}
}
四、Vue 3 ts 调用子组件方法
在 Vue 3 中,我们可以使用 TypeScript 去定义组件并且更好地支持类型检查。在 TypeScript 中调用子组件方法与 JavaScript 中大体相同,需要在 Vue 组件 TypeScript 类型定义中定义 ref 属性,然后可以使用它来调用子组件方法。
import { defineComponent, ref } from 'vue';
const ChildComponent = defineComponent({
methods: {
hello() {
console.log('Hello from ChildComponent!');
}
}
});
export default defineComponent({
components: { ChildComponent },
setup() {
const childRef = ref(null);
return { childRef };
},
methods: {
callChildMethod() {
this.childRef?.hello();
}
}
});
五、Vue 3 父组件调用子组件方法
在 Vue 3 中,父组件调用子组件方法也有两种方式。一种是直接在父组件中获取到子组件实例引用,通过该引用调用子组件方法;另外一种是使用 provide / inject 的方式进行传递。提前告诉大家,第一种方式比较限制,不如第二种方式做得好。
import { defineComponent, ref } from 'vue';
const ChildComponent = defineComponent({
methods: {
hello() {
console.log('Hello from ChildComponent!');
}
}
});
export default defineComponent({
components: { ChildComponent },
setup() {
const childRef = ref(null);
return { childRef };
},
mounted() {
this.childRef = this.$refs.child;
},
methods: {
callChildMethod() {
this.childRef?.hello();
}
}
});
六、Vue 3 子组件调用父组件方法
在 Vue 3 中,子组件如何调用父组件的方法与 Vue 2 中基本相同,但也有一些细微的变化。我们可以向上通过 emit 事件传递数据,使得父组件可以接收到子组件传递的数据。
const ChildComponent = {
methods: {
handleClick() {
this.$emit('hello');
}
}
};
const ParentComponent = {
components: { ChildComponent },
methods: {
sayHello() {
console.log('Hello from ParentComponent!');
}
},
template: '
原创文章,作者:YBRX,如若转载,请注明出处:https://www.506064.com/n/141993.html