Vue ref 属性

ref 被用来给元素或子组件注册引用信息(id的替代者)。

  • 应用在html标签上获取的是真实DOM元素,应用在组件标签上获取的是组件实例对象VC
  • 使用方式
    • 打标识:

      或 想当于 id=“xxx”
    • 获取: this.$refs.xxx或 document.getElementById(“xxx”)
<template>
  <div>
    <h1 v-text="msg" ref="title"></h1>
    <button ref="btn" @click="showDOM">点我输出上方的DOM元素</button>
    <School ref="sch"/>
  </div>
</template>

<script>
  import School from './components/School'

  export default {
    
    
    name:'App',
    components:{
    
     School },
    data() {
    
    
      return {
    
    
        msg:'欢迎学习Vue!'
      }
    },
    methods: {
    
    
      showDOM(){
    
    
        console.log(this.$refs.title)	// 真实DOM元素
        console.log(this.$refs.btn)		// 真实DOM元素
        console.log(this.$refs.sch)		// School组件的实例对象(vc)
      }
    },
  }
</script>

猜你喜欢

转载自blog.csdn.net/fd2025/article/details/125326709
今日推荐