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

$refs access DOM in Vue (detailed tutorial)

亚连
亚连Original
2018-06-19 17:53:552312browse

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;)
    }
  }
})

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 bb9345e55eb71822850ff156dfde57c8 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>

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);
    }
  }
})

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
    }
  }
})

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>

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 4a249f0d628e2318394fd9b75b4636b1 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);

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>

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;
    }
  }
});

效果如下:

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

相关文章:

有关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:
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