这个是自闭合
替代<School></School>

2A476F3A-6737-48BE-9BC1-B349B76363D9_1_105_c.jpeg

Vue中如何操作Dom元素呢? 使用ref属性

我们之前是通过什么方式获得Dom的呢?
看下面的例子
通过document.getElementById(“hello”)

  1. <template>
  2. <div>
  3. <School/>
  4. <h3 id="hello" > 我就是你想获得的Dom元素</h3>
  5. <button @click="ShowDom">点我显示Dom</button>
  6. </div>
  7. </template>
  8. <script>
  9. //引School组件
  10. import School from "@/components/School";
  11. export default {
  12. name: 'App',
  13. components : {School},
  14. methods:{
  15. ShowDom(){
  16. console.log(document.getElementById("hello"))
  17. }
  18. }
  19. }
  20. </script>
  21. <style>
  22. </style>

image.png

但是在Vue中操作Dom这种事情还有一种更加方便的方法
我们可以通过ref属性来获得相关的Dom

this.$refs.hello

<template>
  <div>
    <School/>
    <h3 ref="hello" > 我就是你想获得的Dom元素</h3>
    <button @click="ShowDom">点我显示Dom</button>
  </div>


</template>

<script>
//引School组件
import School from "@/components/School";

export default {
  name: 'App',
  components : {School},
  methods:{
    ShowDom(){
      console.log(this.$refs.hello)
    }
  }
}
</script>

<style>

</style>

最重要的事情是这样,如果我们在School这个标签上标记 ref,那么我们会得到什么呢???

image.png

那么我们得到的是什么呢?

我们发现我们得到了Vc (也就是Vue的实例)

image.png

那么既然我可以得到Dom实例,我就可以做很多事情了

image.png