current position:Home>vue3. 0 dynamically bind and obtain DOM through ref;

vue3. 0 dynamically bind and obtain DOM through ref;

2022-04-29 17:20:24HHH 917

describe

because vue3.0 Not directly this.$refs Get bound ref dom Elements
vue3.0 Only by The way binding dom

//html
<div :ref="refDiv"></div>

//setup  in 
const refDiv = ref();
return{
    
refDiv
}

But this binding dom It's not dynamic Variables are written dead
If traversal binds multiple dom It doesn't work
Then I studied the following methods

adopt Dynamic binding attribute Attribute and ref Binding function Implementation dynamics ref

dom Element dynamic binding Custom properties

<div
   :name="scope.$index"
   :ref="getStartRef"
   > Start </div>

getStartRef ref Bound function Use one The variable object is saved Current ref The format is
Dynamically bound custom attribute string : Obtained by the current function ref
By function You can get the currently bound function ref adopt $attrs Property to get custom properties attribute attribute ( Such as :name)

 let startRef = {
    }
const getStartRef = (el) => {
    
      if ((el && el.$attrs['name'] >= 0) || (el && el.$attrs['name'])) {
    
        startRef[el.$attrs['name']] = el
        console.log('el', el.$attrs['name'])
      }
    }

 Insert picture description here
So when we can pass startRef Get the specified dom;

Get the specified dom;

//html
<div
   :name="scope.$index"
   :ref="getStartRef"
   @click='clickHandler(scope.$index)'
   > Start </div>
//setup
setup(){
    
	let startRef = {
    }
	const getStartRef = (el) => {
    
	      if ((el && el.$attrs['name'] >= 0) || (el && el.$attrs['name'])) {
    
	        startRef[el.$attrs['name']] = el
	        console.log('el', el.$attrs['name'])
	      }
	    }
	
	const clickHandler = (index)=>{
    
	console.log('startRef[index] ',startRef[index] );
	}
	return {
    
	startRef,
	clickHandler 
	}
}

copyright notice
author[HHH 917],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204291525470161.html

Random recommended