美文网首页
Vue的ref的使用

Vue的ref的使用

作者: coderhzc | 来源:发表于2022-01-10 17:43 被阅读0次

    一.什么是ref ?

    ref用来辅助我们获取DOM元素或组件的引用实例对象,
    每个vue的组件实例上,都包含一个refs对象,里面存储着对应的DOM元素或组件的引用,默认情况下,组件的refs指向一个空对象

    实际截图:

    image.png

    二.标签的具体使用方法:

    2.1具体使用流程

    // 第一步: 在标签或者组件元素上 写上一个res="自定义名称"
    <h1 ref="myh1"></h1>
    <button @click="getEle"></button>
    methods:{
        getEle() {
          // 第二步: 固定写法
          consoloe.log(this.$refs.myh1); // 得到的就是你当前的 <h1 class="title" ref="myh1">App根组件</h1>标签
        }
    }
    
    image.png

    三.组件的具体使用方法

    组件中使用ref截图

    image.png

    总结: ref定义的属性名不能冲突要是写的一样的话,后面的会覆盖前面的

    四.ref结合this.$nexitick方法的综合案例

    this.$nextTick 的使用方法:

    image.png

    具体代码

    <template>
      <div id="app">
        <!-- 1.ref="自定义属性名" 固定写法 -->
        <h1 class="title" ref="myh1">App根组件</h1>
        <button @click="showThis">打印 this</button> <br />
    
        <button @click="showAdd">调用Left组件的add 方法</button>
        <hr />
        <Left ref="leftCpn"></Left>
        <Right></Right>
    
        <hr />
        <div class="demo-box">
          <h1>案例演示</h1>
          <input type="text" v-if="show" @blur="showbutton" ref="iptRef" />
          <button @click="btnChangeShow" v-else>展示输入框</button>
        </div>
      </div>
    </template>
    
    <script>
    import Left from "@/components/Left.vue";
    import Right from "@/components/Right.vue";
    export default {
      name: "App",
      components: {
        Left,
        Right,
      },
      data() {
        return {
          show: false,
        };
      },
    
      methods: {
        btnChangeShow() {
          // 1.切换布尔值,把文本框展示出来
          this.show = true;
          // 2.让展示出来的文本框,自动获取焦点
          console.log(this.$refs.iptRef); // undefined 这种是拿不到值的 因为在生命周期beforUpdate更新了最新的数据,但是页面还没有渲染,
          // 所以要是用 this.$nextTick 去实现,类似于setTimeOut延迟的效果,延迟到DOM渲染完成以后再去执行对应的操作
          this.$nextTick(() => {
            this.$refs.iptRef.focus();
          });
        },
        showbutton() {
          this.show = false;
        },
        showAdd() {
          this.$refs.leftCpn.addOne();
        },
        showThis() {
          console.log(this);
          console.log(this.$refs.myh1);
          this.$refs.myh1.style.backgroundColor = "yellow";
        },
      },
    };
    </script>
    
    <style lang="less" scoped>
    #app {
      .title {
        background-color: #ccc;
      }
      .demo-box {
        background-color: #ccc;
      }
    }
    </style>
    
    
    image.png

    相关文章

      网友评论

          本文标题:Vue的ref的使用

          本文链接:https://www.haomeiwen.com/subject/fgomcrtx.html