Home > Web Front-end > Vue.js > body text

A brief discussion on the use of $refs in vue.js (with code)

青灯夜游
Release: 2021-02-16 09:31:13
forward
2545 people have browsed it

A brief discussion on the use of $refs in vue.js (with code)

Related recommendations: "vue.js Tutorial"

  • Description: vm.$refs is an object , holds all sub-components (or HTML elements) that have registered ref

  • Usage: In the HTML element, add the ref attribute, and then pass the vm.$refs. attribute in JS To get

  • Note: If you are getting a subcomponent, you can get the data and methods in the subcomponent through ref

Generally speaking, to get the DOM element, you need document.querySelector(".input1") Get the dom node, and then get the value of input1.

But after binding with ref, we no longer need to obtain the dom node. We can directly bind input1 to the above input and then call it in $refs.

Then call this in javascript: this.$refs.input1 This will reduce the consumption of obtaining dom nodes. The sample code is as follows:

<-- 添加ref属性 -->
<div id="app">
	<input type="text" ref="input1"/>
    <button @click="add">添加</button>
</div>

// 获取注册过 ref 的所有组件或元素
<script>
    new Vue({
        el: "#app",
        methods:{
        add:function(){
            this.$refs.input1.value ="22"; //this.$refs.input1  减少获取dom节点的消耗
            }
        }
    })
</script>
Copy after login

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of A brief discussion on the use of $refs in vue.js (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!