Vue

ref 的使用

芸殇
2022-02-01 / 0 评论 / 380 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年02月25日,已超过1709天没有更新,若内容或图片失效,请留言反馈。

Vue 中 ref 的使用

Vue2 中使用 ref

父组件

<template>
  <hello-world ref='son'></hello-world>
  <button @click='getSon'>获取</button>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
  components: {
    HelloWorld
  },
  data() {
    return {
      
    }
  },
  methods: {
    getSon() {
      // 父组件获取子组件的属性和调用子组件的方法
      console.log(this.$ref.son.title)
      this.$ref.son.sonMethod()
    }
  }
}
</script>

子组件

<template>
  <div> {{ title }} </div>
</template>

<script>
  export default {
    name: 'Son',
    data() {
      return {
        title: '我是子组件的标题'
      }
    },
    methods: {
      sonMethod() {
        console.log('我是子组件的方法')
      }
    }
  }
</script>
0

评论 (0)

取消