Vue访问子组件实例或子元素

3,592 阅读1分钟

尽管存在prop和事件,有的时候你仍需要在JavaScript里直接访问一个子组件。

首先给子组件上添加一个ref属性

<base-alert ref="baseAlert"></base-alert>

现在可以使用

this.$refs.baseAlert

来访问子组件 base-alert的方法, 比如点击父组件的按钮,调用子组件的方法。

<template>
    <base-alert ref="baseAlert"></base-alert>
    <div @click="clickMe">click me</div>
</template>

<script>
import BaseAlert from '@/components/BaseAlert'

export default {
    components: {
        BaseAlert
    },
    methods: {
        clickMe () {
          //popUp 方法在子组件中定义
          this.$refs.baseAlert.popUp()
        }
    }
}
</script>

<style scoped>
div {
  width: 20px;
  height: 20px;
  background: red;
  margin-top: 100px
}
</style>
//子组件

<template>
  <div>
    <div>child component</div>
  </div>
</template>
<script>
export default {
  data () {
    return {
    }
  },
  methods: {
    popUp () {
      alert(11)
    }
  }
}

</script>