27-Vue脚手架-ref属性

发布时间 2023-10-19 16:49:32作者: 马铃薯1

ref 属性

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

1)应用在 html标签上获取的是真实DOM元素,应用在组件标签上获取的是组件实例对象vc(VueComponent)

2)使用方式

  • 打标识:<h1 ref="xxx"></h1> 或 <School ref=''xxx'></School>
  • 获取:this.$refs.xxx

src/components/Student.vue

<template>
  <div class="schoolStyle">
    <h2>学校名称:{{name}}</h2>
    <h2>学校地址:{{address}}</h2>
  </div>
</template>

<script>
  export default{
    // eslint-disable-next-line vue/multi-word-component-names
    name:"School",
    data(){
      return{
        name:"东华理工大学",
        address:"江西南昌"
      }
    }
  }

</script>

<style>
  .schoolStyle{
    background-color: gray;
  }
</style>

src/App.vue(这里是重点,ref 属性)

<template>
  <div>
    <!--<h1 v-text="msg" id="title"></h1>-->
    <h1 v-text="msg" ref="title"></h1>
    <button ref="btn" @click="showDOM">点击输出上方的DOM元素</button>
    <hr/>
    <School id="sch1"></School>
    <School ref="sch2"></School>
  </div>
</template>

<script>
  // 引入School组件
  import School from "./components/School"

  export default{
    name:"App",
    data(){
      return{
        msg:"欢迎学习Vue!"
      }
    },
    components:{
      School:School,
    },
    methods:{
      showDOM(){
        // ref 在html标签上获取的是真实DOM元素
        // console.log(document.getElementById("title"))
        console.log(this.$refs.title)
        console.log(this.$refs.btn)

        // ref 在组件标签上获取的是组件实例对象
        console.log(document.getElementById("sch1"))
        console.log(this.$refs.sch2)
      }
    }
  }
</script>

src/main.js

import Vue from "vue"
import App from "./App.vue"

// 阻止 vue 在启动时生成生产提示
Vue.config.productionTip = false

new Vue({
    el:"#app",
    render:h => h(App)
})