Vue:ref(获得dom元素)

Vue使用ref给template的dom元素设置身份

用法类似(id=“ ”)====》(ref=“ ”)
使用时候:this.$refs.名字

ref的使用:获取Vue的dom
<!--只认识三个标签-->
<template>
 <!--组件结构-->
  <div>
    <h1 id="hh">{{schoolname}}</h1>
      <button @click="showdom">点我</button>
    <h2 ref="sss">{{adress}}</h2>
    <Student ref="student"></Student>
  </div>
</template>

<script>

    /*组件引入*/
    import Student from './student'

    /*组件交互代码js*/
    export default {
        name: "School",
      data(){
        return {
          schoolname:"六中",
          adress:"福建"
        }
      },methods:{
            /*有时候我们需要获得dom元素*/
            showdom(){
                /*使用原来的dom有违背Vue的初衷(需要配置id通过document获得)*/
                console.log(document.getElementById("hh"))
                /*于是vue引入了ref*/
                console.log(this)/*现在输出this:是vc对象*/
                /*通过this.$refs.名字获得*/
                console.log(this.$refs.sss)
                /*那么ref可以当成id使用*/
                /*当ref放在注册的组件的时候会得到什么*/
                console.log(this.$refs)/*直接获得所有dom元素的数组*/
                console.log(this.$refs.student)/*获得的是组件对象:用于组件通讯*/
            }

        },
      components:{
        Student
      }
    }
</script>

<style scoped>


</style>


上一篇:Vue进阶(幺捌贰):父子组件元素获取、方法互相调用


下一篇:C# virtual 和 abstract 区别