Home >Web Front-end >Vue.js >A brief discussion on the use of $refs in vue.js (with code)

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

青灯夜游
青灯夜游forward
2021-02-16 09:31:132650browse

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>

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete