vue利用ref获取子组件的数据

利用ref获取子组件的实例,并在实例中获取到子组件数据

父组件代码

<template>
  <div>
    <son ref="son" />
    <h1>父组件:{
    
    { data }}</h1>
  </div>
</template>

<script>
import son from '@/components/SonFile.vue'  

export default {
  data() {
    return {
      data: ''
    }
  },
  components: {
    son
  },
  mounted() {
    console.log(this.$refs.son, "我是子组件的实例")
    this.data = this.$refs.son.sonData//获取到子组件的数据进行赋值
  },
}
</script>

子组件代码

<template>
  <div class="son">
    <h1>{
    
    { sonData }}</h1>
  </div>
</template>

<script>
export default {
  components: {

  },
  data() {
    return {
      sonData: '我是子组件的数据'
    }
  },
  computed: {

  },
  created() {//创建后
  },
  mounted() {//载入后
  },
  unmounted() {//销毁后
  },
  methods: {
    sonUpdate() {
      this.sonData = '子组件的数据改变了'
    }
  },
}
</script>

<style lang="scss" scoped>
.son {
  width: 300px;
  height: 300px;
}
</style>

如图

在父组件中我们需要把获取子组件实例和获取子组件数据放在mounted中,因为如果子组件并未加载完成,在$refs获取时将会找不到目标。所以在父组件输出$refs获取的数据时,不能直接使用。

<template>
  <div>
    <son ref="son" />
    <h1>父组件:{
    
    { this.$refs.son.sonData }}</h1>
  </div>
</template>
//直接在父组件使用将会找不到子组件实例

猜你喜欢

转载自blog.csdn.net/m0_60322614/article/details/128672176