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()
  • 相关阅读:
    使用sourcetree 出现 For user git on host github.com 解决方案
    iOS App Store下载的付费软件 重新签名后 安装到未越狱的手机上
    Swift 入门之简单语法(一)
    [转]C语言指针 之 结构体指针
    Xcode 菜单详解 [转载自用]
    C语言笔记-字符串+转义符(写起来想砸键盘)
    C语言笔记-getchar等蛋疼设定 [可能已解决]
    C语言笔记-枚举类型
    C语言笔记-数据类型长度
    C语言笔记-函数-存储期和作用域
  • 原文地址:https://www.cnblogs.com/dianzan/p/12403353.html
Copyright © 2011-2022 走看看