<template>
  <div>
    <div ref="hello">
      hello world
    </div>
    <button @click="handleClick">我是按钮</button>
  </div>
</template>

<script>
export default {
  name: 'Home',
  data () {
    return {
      arr: ''
    }
  },
  methods: {
    handleClick () {
      this.arr = this.$refs.hello.innerHTML //获取DOM元素节点的值
      alert(this.arr)
    }
  }
}
</script>

 

vue $refs的基本用法

<div id="app">
    <input type="text" ref="input1"/>
    <button @click="add">添加</button>
</div>
<script>
new Vue({
    el: "#app",
    methods:{
    add:function(){
        this.$refs.input1.value ="22"; //this.$refs.input1  减少获取dom节点的消耗
        }
    }
})
</script>

一般来讲,获取DOM元素,需document.querySelector(".input1")获取这个dom节点,然后在获取input1的值。

但是用ref绑定之后,我们就不需要在获取dom节点了,直接在上面的input上绑定input1,然后$refs里面调用就行。

然后在javascript里面这样调用:this.$refs.input1  这样就可以减少获取dom节点的消耗了

refs的坑
 <div class="slider-group" ref="sliderGroup">
      <slot>
      </slot>
   
    </div>

该数据来源先是发送ajax请求获取数据再渲染dom
在mounted中调用

// console.log(this.$refs.sliderGroup.children)
        this.children = this.$refs.sliderGroup.children

今天在调试的时候,发现console.log(this.$refs.sliderGroup.children)能取到该dom集合
但在

        this.children = this.$refs.sliderGroup.children
赋值的时候, this.children始终取不到
一开始,以为 是 类数组对象的问题 然后各种类数组转数组的方法,尝试失败,一度怀疑人生
console.log的坑 虽然能打印出来,但是dom并没有渲染完毕
解决
  mounted() {
      // setTimeout(() => {
      //   this._setSliderWidth()
      //   this._initDots()
      //   this._initSlider()
      //   if (this.autoPlay) {
      //     this._play()
      //   }
      // }, 20)
      let length = this.$refs.sliderGroup.children.length
      const fecthChil = () => {
        window.setTimeout(() => {
          length = this.$refs.sliderGroup.children.length
          // console.log('.....', length)
          if (length <= 0) fecthChil()
          // const chi  = Array.from(this.$refs.sliderGroup.children)
          // console.log('233c', chi)
          this._setSliderWidth()
          this._initDots()
          this._initSlider()
          if (this.autoPlay) {
            this._play()
          }
        }, 300)
      }
      fecthChil()