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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM