zoukankan      html  css  js  c++  java
  • 通过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()
  • 相关阅读:
    申请奖励加分
    寒假学习01
    加分项及建议
    12月30日总结
    12月17日 期末总结
    12月31日总结
    12月15日总结
    12月28日总结
    01月03日总结
    01月05日总结
  • 原文地址:https://www.cnblogs.com/dianzan/p/12403353.html
Copyright © 2011-2022 走看看