Home Web Front-end JS Tutorial $refs access DOM in Vue (detailed tutorial)

$refs access DOM in Vue (detailed tutorial)

Jun 19, 2018 pm 05:53 PM
refs vue access

This article mainly introduces the Vue 2.0 study notes on using $refs to access the DOM in Vue. Now I share it with you and give it as a reference.

Through the previous study of Vue, it is necessary for us to further understand some special properties and methods in Vue instances. The first thing to understand is the $refs attribute. But before we dive into the JavaScript part, let's take a look at templates.

<p id="app">
  <h1>{{ message }}</h1>
  <button @click="clickedButton">点击偶</button>
</p>

let app = new Vue({
  el: &#39;#app&#39;,
  data () {
    return {
      message: &#39;Hi,大漠!&#39;
    }
  },
  methods: {
    clickedButton: function () {
      console.log(&#39;Hi,大漠!&#39;)
    }
  }
})
Copy after login

In Vue's template, we can add the ref attribute to any element in the template, so that these elements can be referenced in the Vue instance. More specifically, DOM elements can be accessed. Try adding the ref attribute to <button> in the example above. This button has been bound to a click event. This event allows us to print Hi, Desert! in the browser's control panel. information.

<button ref="myButton" @click="clickedButton">点击偶</button>
Copy after login

Note that the ref attribute is not a standard HTML attribute, but an attribute in Vue. In fact, it won't even be part of the DOM, so when you look at the rendered HTML in a browser, you won't see anything about ref. Because there is no : added in front of it, and it is not a directive.

Use the $refs property on the Vue instance to reference this button through myButton. Let's see what it looks like when printed out in the browser's console.

let app = new Vue({
  el: &#39;#app&#39;,
  data () {
    return {
      message: &#39;Hi!大漠&#39;
    }
  },
  methods: {
    clickedButton: function () {
      console.log(this.$refs);
    }
  }
})
Copy after login

If you open the browser console, we can see that this attribute is a JavaScript object, which contains references to all elements of the ref attribute.

Note that the key name in this object (key) is the same as the name we specified in the ref attribute (name) matches, and its value (value) is a DOM element. In this case, we can see that the key name is myButton, and its value is the button element. And this has nothing to do with Vue.

So in Vue, you can access the DOM element by accessing the name of the ref on the $refs object. Consider the following example. After we click the button, the text of the button will change the value in the message data.

let app = new Vue({
  el: &#39;#app&#39;,
  data () {
    return {
      message: &#39;Hi!大漠&#39;
    }
  },
  methods: {
    clickedButton: function () {
      console.log(this.$refs)
      this.$refs.myButton.innerText = this.message
    }
  }
})
Copy after login

After clicking the button, the text of the button will change to "Hi,! Desert":

Of course, we can also This effect is achieved by using query selectors to access DOM elements, but using the ref attribute is more concise, and this is also the method in Vue. It will also be more secure since you won't be relying on class and id. Therefore, there is almost no impact from changing HTML tags or CSS styles.

One of the main purposes of JavaScript frameworks like Vue is to relieve developers from having to deal with the DOM. So you should avoid doing things like this unless you really need to. There is also a potential problem that should be noted.

First let’s look at a simple example, adding a ref attribute to the h1 element.

{{ message }}

<button ref="myButton" @click="clickedButton">点击偶</button>

Copy after login

When we click the button, the value output by the browser console will change:

Because we assigned the Vue instance to the variable app, so we can continue to use it. What we need to do now is change the text of the element. Initially, the content of the <h1> element is the value of message. In the following example, look at the element <h1&gt through a setTimeout ;Changes that occurred:

let app = new Vue({
  el: &#39;#app&#39;,
  data () {
    return {
      message: &#39;Hi!大漠&#39;
    }
  },
  methods: {
    clickedButton: function () {
      console.log(this.$refs);
      this.$refs.myButton.innerText = this.message
    }
  }
})

setTimeout(function() {
  app.$refs.message.innerText = &#39;延迟2000ms修改h1元素的文本&#39;;
}, 2000);
Copy after login

As you can see, we are overwriting the changes we made to the DOM when updating the data attribute. The reason for this is that when accessing DOM elements and manipulating them directly, you actually skip the virtual DOM discussed in the previous article. Therefore, Vue still controls the h1 element, and even when Vue makes an update to the data, it updates the virtual DOM and then updates the DOM itself. Therefore, you should be careful with direct changes to the DOM, as any changes you make may be overwritten even if you accidentally make changes. Although you should be careful when changing the DOM when using refs, it is relatively safe to do read-only operations, such as reading values ​​from the DOM.

Also, let’s take a look at the effect of using the refs attribute in the v-for directive. For example, in the following example, given an unordered list ul, the numbers from 1 to 10 are output through the v-for instruction.

<ul>
  <li v-for="n in 10" ref="numbers">{{ n }}</li>
</ul>
Copy after login

When you click the button, the $refs attribute will be output in the browser console:

正如上图所看到的一样,把numbers属性添加到了对象中,但需要注意该值的类型。与之前看到的DOM元素不同,它实际上是一个数组,一个DOM元素的数组。当使用ref属性和v-for指令时,Vue会迭代所有DOM元素,并将它们放置在数组中。在这种情况下,这就输出了10li的DOM元素的数组,因为我们迭代了10次。每个元素都可以像我们之前看到的那样使用。

上面通过简单的示例了解了Vue中的$refs在Vue中是怎么访问到DOM元素的。接下来看一个简单的示例。

在Web中Modal组件是经常可见的一个组件。来看看$refs怎么来来控制Modal的打开和关闭。

<!-- HTML -->
<p id="app">
  <p class="actions">
    <button @click="toggleModal(&#39;new-item&#39;)">添加列表</button>
    <button @click="toggleModal(&#39;confirm&#39;)">删除列表</button>
  </p>

  <modal ref="new-item">
    <p>添加新的列表</p>
    <p slot="actions">
    <button>保存</button>
    <button>取消</button>
    </p>
  </modal>
  <modal ref="confirm">
    <p>删除列表?</p>
    <p slot="actions">
    <button>删除</button>
    <button>取消</button>
    </p>
  </modal>

  <script type="x-template" id="modal-template">
    <transition name="modal-toggle">
    <p class="modal" v-show="toggle">
      <button class="modal__close" @click="close">X</button>
      <p class="modal__body">
      <h1>Modal</h1>
      <slot>这是一个Modal,是否需要添加新的内容?</slot>
      </p>
      <p class="modal__actions">
      <slot name="actions">
        <button @click="close">关闭</button>
      </slot>
      </p>
    </p>
    </transition>
  </script>
</p>

// JavaScript
let Modal = Vue.component(&#39;modal&#39;, {
  template: "#modal-template",
  data () {
    return {
    toggle: false
    }
  },
  methods: {
    close: function() {
    this.toggle = false;
    }
  }
});
let app = new Vue({
  el: "#app",
  methods: {
    toggleModal(modal) {
    this.$refs[modal].toggle = !this.$refs[modal].toggle;
    }
  }
});
Copy after login

效果如下:

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

有关ES6中Proxy的使用说明

在Vue中详细介绍$attrs属性

详细介绍ES6中的代理模式(Proxy)

The above is the detailed content of $refs access DOM in Vue (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

How to jump to the div of vue How to jump to the div of vue Apr 08, 2025 am 09:18 AM

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.

See all articles