通過ref來獲取DOM節點


<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()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM