• 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
  • 相关阅读:
    24. Swap Nodes in Pairs(M);25. Reverse Nodes in k-Group(H)
    61. Rotate List(M);19. Remove Nth Node From End of List(M)
    素数筛选法(prime seive)
    哈夫曼树;二叉树;二叉排序树(BST)
    sort与qsort的区别与联系
    贪心算法
    First non-repeating character in a stream
    transform
    C++11 & C++14 & C++17新特性
    开个玩笑
  • 原文地址:https://www.cnblogs.com/pingming/p/14850653.html
Copyright © 2020-2023  润新知