Vue3.0:如何在父组件中调用ref的子组件方法

在使用vue3.0的时候,需要去调取子组件的方法去快速的解决需求,类似于在Vue2.x中的this.$refs去操作虚拟dom元素的方法,但是在Vue3.0中是没有this指向的,那么解决办法就是先将ref的值定义一个对象,其value值再指向是子组件component。


//子页面 Child.vue
<template>
  <div>子页面计数:{{ count }}</div>
</template>

<script>
import { ref } from "vue";

export default {
  name: "Child",
  setup() {
    const count = ref(0);

    const add = () => {
      count.value++;
    };

    const addCustom = (value) => {
      count.value += value;
    };

    return {
      count,
      add,
      addCustom,
    };
  },
};
</script>

<style lang="scss" scoped>
</style>

 

// 父页面 Index.vue
<template>
  <div>
    <Child ref="child"></Child>
    <br />
    父页面按钮:<button @click="handleAdd">点击+1</button>
    <br />
    父页面按钮:<button @click="handleAddCustom">(添加自定义数值)点击+10</button>
  </div>
</template>

<script>
import { ref } from "vue";
import Child from "./Child";

export default {
  name: "Parent",
  components: {
    Child,
  },
  setup() {
    const child = ref();

    const handleAdd = () => {
      child.value.add();
    };
    const handleAddCustom = () => {
      child.value.addCustom(10);
    };

    return {
      child,
      handleAdd,
      handleAddCustom
    };
  },
};
</script>

<style lang="scss" scoped>
</style>

 

上面展示的是我的代码实现,代码逻辑是我计数,但是当把这个组件以子组件的方式引进去的时候,我想直接通过调用子组件的方法去实现数字的累加。
 

 上图为界面。

 
 
 
 
转载链接:https://www.jianshu.com/p/846e1157b96b
posted @ 2021-06-04 17:54  平民的麦田  阅读(8921)  评论(0编辑  收藏  举报