vue父组件调用子组件方法

7,929 阅读1分钟

总结两条父组件调用子组件方法的步骤。

  1. 直接在父组件内部给子组件标签添加ref属性,然后通过ref属性来调用子组件的方法。

    // 父组件
    <template>
      <div>
        <button @click="handleClick">按钮</button>
        <Child ref="child"></Child>
      </div>
    </template>
    ​
    ​
    <script>
    import Child from './components/child.vue'
    export default {
      components: {
        Child,
      },
      methods: {
        handleClick() {
          this.$refs.child.sing()
        },
      },
    }
    </script>
    ​
    // 子组件
    <template>
      <div>
        <p>我是子组件</p>
      </div>
    </template><script>
    export default {
      methods: {
        sing() {
          console.log('使用refs直接调用函数方法')
        },
      },
    }
    </script>
    
  2. 在子组件的挂载阶段给nextTick里面注册on发送一个函数,然后在父组件里面通过ref属性.on发送一个函数,然后在父组件里面通过ref属性.emit来调用子组件函数

    // 父组件
    <template>
      <div>
        <button @click="handleClick">按钮</button>
        <Child ref="child"></Child>
      </div>
    </template><script>
    import Child from './components/child.vue'
    export default {
      components: {
        Child,
      },
      methods: {
        handleClick() {
          this.$refs.child.$emit("sing")
        },
      },
    }
    </script>
    ​
    // 子组件
    <template>
      <div>
        <p>我是子组件</p>
      </div>
    </template><script>
    export default {
      mounted() {
        this.$nextTick(function () {
          this.$on('sing', function () {
            console.log('$emit配合$on实现')
          })
        })
      },
    }
    </script>