How to use $refs and $nextTick in Vue
This article mainly explains "how to use $refs and $nextTick in Vue". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor learn how to use $refs and $nextTick in Vue.
1. Brief introduction to $refs
Refs is the method provided by vue to get the real dom.
$refs gets the DOM element
[usage steps]:
Add ref attribute to native DOM element and use this.$refs to get native DOM element
[code demonstration]:
Get the native DOM element I am the h5 tag export default {/ / get the native dom mounted () {console.log (document.getElementById ("h")) after mounting; / / this.$refs is the unique attribute console.log (this.$refs.myH) in the vue object;},}
[console effect]:
$refs gets the component object
[code demonstration]:
Get component object import Demo from "@ / components/Demo"; export default {mounted () {console.log (this.$refs.myCom); / / get subcomponent object let demo = this.$refs.myCom; / / call method demo.fn () in subcomponent;}, components: {Demo,},}
[effect display]:
2. Basic use of $nextTick
$nextTick executes the function body in the method after waiting for the dom update
Vue updates DOM asynchronously
[vue Asynchronous Update Demo]:
Get component object import Demo from "@ / components/Demo"; export default {mounted () {console.log (this.$refs.myCom); / / get subcomponent object let demo = this.$refs.myCom; / / call method demo.fn () in subcomponent;}, components: {Demo,},}
[effect demonstration]:
Use $nextTick to solve the above problems
[code demonstration]:
Vue updates dom asynchronously
{{count}}
Click + 1 to get the data export default {data () {return {count: 0,};}, methods: {add1 () {this.count++; / / console.log (this.$ refs.mycount [XSS _ clean]) / / resolve the asynchronous update problem / / after the dom update is completed, the function body this.$nextTick (()) in this.$nextTick () will be executed sequentially. {console.log (this.$ refs.mycount [XSS _ clean]);});},},}
[effect demonstration]:
$nextTick usage scenario
[code demonstration]:
$nextTick () usage scenario
Click-search export default {data () {return {isShow: false,};}, methods: {search () {this.isShow = true; this.$nextTick (() = > {this.$refs.search.focus ();});},},}
[effect]:
At this point, I believe you have a better understanding of "how to use $refs and $nextTick in Vue". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!