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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

What is the method of converting Vue.js strings into objects? What is the method of converting Vue.js strings into objects? Apr 07, 2025 pm 09:18 PM

Using JSON.parse() string to object is the safest and most efficient: make sure that strings comply with JSON specifications and avoid common errors. Use try...catch to handle exceptions to improve code robustness. Avoid using the eval() method, which has security risks. For huge JSON strings, chunked parsing or asynchronous parsing can be considered for optimizing performance.

Vue realizes marquee/text scrolling effect Vue realizes marquee/text scrolling effect Apr 07, 2025 pm 10:51 PM

Implement marquee/text scrolling effects in Vue, using CSS animations or third-party libraries. This article introduces how to use CSS animation: create scroll text and wrap text with &lt;div&gt;. Define CSS animations and set overflow: hidden, width, and animation. Define keyframes, set transform: translateX() at the beginning and end of the animation. Adjust animation properties such as duration, scroll speed, and direction.

How to use export default and import in Vue How to use export default and import in Vue Apr 07, 2025 pm 07:09 PM

export default is used to export Vue components and allow other modules to access. import is used to import components from other modules, which can import a single or multiple components.

Vue and Element-UI cascaded drop-down box props pass value Vue and Element-UI cascaded drop-down box props pass value Apr 07, 2025 pm 07:36 PM

The data structure must be clearly defined when the Vue and Element-UI cascaded drop-down boxes pass the props, and the direct assignment of static data is supported. If data is dynamically obtained, it is recommended to assign values ​​within the life cycle hook and handle asynchronous situations. For non-standard data structures, defaultProps or convert data formats need to be modified. Keep the code simple and easy to understand with meaningful variable names and comments. To optimize performance, virtual scrolling or lazy loading techniques can be used.

What does the vue component pass value mean? What does the vue component pass value mean? Apr 07, 2025 pm 11:51 PM

Vue component passing values ​​is a mechanism for passing data and information between components. It can be implemented through properties (props) or events: Props: Declare the data to be received in the component and pass the data in the parent component. Events: Use the $emit method to trigger an event and listen to it in the parent component using the v-on directive.

What does it mean to lazy load vue? What does it mean to lazy load vue? Apr 07, 2025 pm 11:54 PM

In Vue.js, lazy loading allows components or resources to be loaded dynamically as needed, reducing initial page loading time and improving performance. The specific implementation method includes using &lt;keep-alive&gt; and &lt;component is&gt; components. It should be noted that lazy loading can cause FOUC (splash screen) issues and should be used only for components that need lazy loading to avoid unnecessary performance overhead.

What method is used to convert strings into objects in Vue.js? What method is used to convert strings into objects in Vue.js? Apr 07, 2025 pm 09:39 PM

When converting strings to objects in Vue.js, JSON.parse() is preferred for standard JSON strings. For non-standard JSON strings, the string can be processed by using regular expressions and reduce methods according to the format or decoded URL-encoded. Select the appropriate method according to the string format and pay attention to security and encoding issues to avoid bugs.

Is the request method (GET, POST, etc.) used correctly? Is the request method (GET, POST, etc.) used correctly? Apr 07, 2025 pm 10:09 PM

The use of Axios request method in Vue.js requires following these principles: GET: Obtain resources, do not modify data. POST: Create or submit data, add or modify data. PUT: Update or replace existing resources. DELETE: Delete the resource from the server.

See all articles