广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >详解Vue中$refs和$nextTick的使用方法
  • 607
分享到

详解Vue中$refs和$nextTick的使用方法

2024-04-02 19:04:59 607人浏览 独家记忆
摘要

目录1、$refs简介$refs获取DOM元素$refs获取组件对象2、$nextTick基本使用Vue异步更新DOM利用$nextTick解决以上问题$nextTick使用场景1、

1、$refs简介

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

$refs获取DOM元素

【使用步骤】:

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

【代码演示】:

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

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

<style>
</style>

【控制台效果】:

$refs获取组件对象

【代码演示】:

<template>
  <div>
    <h1>获取组件对象</h1>
    <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>

【效果展示】:

2、$nextTick基本使用

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

vue异步更新DOM

【vue异步更新演示】:

<template>
  <div>
    <h1>获取组件对象</h1>
    <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>

【效果演示】:

利用$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>

【效果演示】:

$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内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: 详解Vue中$refs和$nextTick的使用方法

本文链接: https://www.lsjlt.com/news/142551.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作