欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2022年03月15日 11:37:11   作者:執(zhí)手天涯@  
這篇文章主要為大家介紹了Vue中$refs和$nextTick的使用方法,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Vue有一定幫助,需要的可以參考一下

1、$refs簡(jiǎn)介

$refs是vue提供的獲取真實(shí)dom的方法。

$refs獲取DOM元素

【使用步驟】:

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

【代碼演示】:

<template>
  <div>
    <h1>獲取原生的DOM元素</h1>
    <h4 id="h" ref="myH">我是h4標(biāo)簽</h4>
  </div>
</template>

<script>
export default {
  // 在掛載之后獲取原生dom
  mounted() {
    console.log(document.getElementById("h"));
    // this.$refs是vue對(duì)象中特有的屬性
    console.log(this.$refs.myH);
  },
};
</script>

<style>
</style>

【控制臺(tái)效果】:

$refs獲取組件對(duì)象

【代碼演示】:

<template>
  <div>
    <h1>獲取組件對(duì)象</h1>
    <Demo ref="myCom"></Demo>
  </div>
</template>

<script>
import Demo from "@/components/Demo";
export default {
  mounted() {
    console.log(this.$refs.myCom);
    // 獲取子組件對(duì)象
    let demo = this.$refs.myCom;
    // 調(diào)用子組件中的方法
    demo.fn();
  },
  components: {
    Demo,
  },
};
</script>

<style>
</style>

【效果展示】:

2、$nextTick基本使用

$nextTick等待dom更新之后執(zhí)行方法中的函數(shù)體

vue異步更新DOM

【vue異步更新演示】:

<template>
  <div>
    <h1>獲取組件對(duì)象</h1>
    <Demo ref="myCom"></Demo>
  </div>
</template>

<script>
import Demo from "@/components/Demo";
export default {
  mounted() {
    console.log(this.$refs.myCom);
    // 獲取子組件對(duì)象
    let demo = this.$refs.myCom;
    // 調(diào)用子組件中的方法
    demo.fn();
  },
  components: {
    Demo,
  },
};
</script>

<style>
</style>

【效果演示】:

利用$nextTick解決以上問題

【代碼演示】:

<template>
  <div>
    <p>vue異步更新dom</p>
    <p ref="mycount">{{ count }}</p>
    <button @click="add1">點(diǎn)擊+1,馬上獲取數(shù)據(jù)</button>
  </div>
</template>

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

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

      // 解決異步更新問題
      // dom更新完成之后會(huì)順序執(zhí)行this.$nextTick()中的函數(shù)體
      this.$nextTick(() => {
        console.log(this.$refs.mycount.innerHTML);
      });
    },
  },
};
</script>

<style>
</style>

【效果演示】:

$nextTick使用場(chǎng)景

【代碼演示】:

<template>
  <div>
    <p>$nextTick()使用場(chǎng)景</p>
    <input
      ref="search"
      v-if="isShow"
      type="text"
      placeholder="這是一個(gè)輸入框"
    />
    <button @click="search">點(diǎn)擊-立即搜索</button>
  </div>
</template>

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

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

<style>
</style>

【效果】:

到此這篇關(guān)于詳解Vue中$refs和$nextTick的使用方法的文章就介紹到這了,更多相關(guān)Vue $refs $nextTick內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論