温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Vue中$refs和$nextTick如何使用

发布时间:2022-03-15 14:46:31 来源:亿速云 阅读:151 作者:iii 栏目:开发技术

本篇内容主要讲解“Vue中$refs和$nextTick如何使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Vue中$refs和$nextTick如何使用”吧!

1、$refs简介

$refs是vue提供的获取真实dom的方法。

$refs获取DOM元素

【使用步骤】:

在原生DOM元素上添加ref属性利用this.$refs获取原生的DOM元素

【代码演示】:

<template>
  <div>
    <h2>获取原生的DOM元素</h2>
    <h5 id="h" ref="myH">我是h5标签</h5>
  </div>
</template>

<script>
export default {
  // 在挂载之后获取原生dom
  mounted() {
    console.log(document.getElementById("h"));
    // this.$refs是vue对象中特有的属性
    console.log(this.$refs.myH);
  },
};
</script>

<style>
</style>

【控制台效果】:

Vue中$refs和$nextTick如何使用

$refs获取组件对象

【代码演示】:

<template>
  <div>
    <h2>获取组件对象</h2>
    <Demo ref="myCom"></Demo>
  </div>
</template>

<script>
import Demo from "@/components/Demo";
export default {
  mounted() {
    console.log(this.$refs.myCom);
    // 获取子组件对象
    let demo = this.$refs.myCom;
    // 调用子组件中的方法
    demo.fn();
  },
  components: {
    Demo,
  },
};
</script>

<style>
</style>

【效果展示】:

Vue中$refs和$nextTick如何使用

2、$nextTick基本使用

$nextTick等待dom更新之后执行方法中的函数体

vue异步更新DOM

【vue异步更新演示】:

<template>
  <div>
    <h2>获取组件对象</h2>
    <Demo ref="myCom"></Demo>
  </div>
</template>

<script>
import Demo from "@/components/Demo";
export default {
  mounted() {
    console.log(this.$refs.myCom);
    // 获取子组件对象
    let demo = this.$refs.myCom;
    // 调用子组件中的方法
    demo.fn();
  },
  components: {
    Demo,
  },
};
</script>

<style>
</style>

【效果演示】:

Vue中$refs和$nextTick如何使用

利用$nextTick解决以上问题

【代码演示】:

<template>
  <div>
    <p>vue异步更新dom</p>
    <p ref="mycount">{{ count }}</p>
    <button @click="add1">点击+1,马上获取数据</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      count: 0,
    };
  },

  methods: {
    add1() {
      this.count++;
      // console.log(this.$refs.mycount.innerHTML);

      // 解决异步更新问题
      // dom更新完成之后会顺序执行this.$nextTick()中的函数体
      this.$nextTick(() => {
        console.log(this.$refs.mycount.innerHTML);
      });
    },
  },
};
</script>

<style>
</style>

【效果演示】:

Vue中$refs和$nextTick如何使用

$nextTick使用场景

【代码演示】:

<template>
  <div>
    <p>$nextTick()使用场景</p>
    <input
      ref="search"
      v-if="isShow"
      type="text"
      placeholder="这是一个输入框"
    />
    <button @click="search">点击-立即搜索</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isShow: false,
    };
  },

  methods: {
    search() {
      this.isShow = true;
      this.$nextTick(() => {
        this.$refs.search.focus();
      });
    },
  },
};
</script>

<style>
</style>

【效果】:

Vue中$refs和$nextTick如何使用

到此,相信大家对“Vue中$refs和$nextTick如何使用”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI