1、 this.$refs.* 拿到虚拟Dom,可以进行真实dom的一切操作

1)在标签中添加ref="*"
2)在方法中用this.$refs.*拿到这个元素,跟document.getElementById('*')一样。

2、自定义指令中,el就是当前环境下的Dom元素

  el.style.color = "yellow";
  console.log(el.tagName);//均可执行

代码:

<!DOCTYPE html>
<html> 
<head>
    <meta charset="utf-8">
    <title>自定义指令</title> 
    <script src="js/vue.js" type="text/javascript"></script> 
    <style type="text/css">
    	.app{
    		width:300px;
    		height: 300px;
    		border: 1px solid #00ff00;
    	}
    /*	.app .child{
    		position: relative;
    		top:320px;
    		width:330px;
    		height: 300px;
    		border: 2px solid red; 
    	}*/
    </style>
</head>
<body> 
	<div class="app">
		<div v-color="colors[1].color1" name="tc">oooooo</div>
		<my-card v-bind:obj="colors" name="zy"> 
		<!-- <div class="child" v-demo:foo.a.b="color2">lalala</div> -->
		</my-card>
	</div> 
	<script>
	/*钩子函数:
		bind、inserted、update、componentUpdated、unbind
	  钩子函数的参数:
	    el、binding、vnode、oldVnode 
	*/
		Vue.directive('color', function (el, binding) {
		  console.log("%%%%拿到当前域的真实dom%%%%");
		  console.log(el);
		  el.style.color = "yellow";
		  console.log(el.tagName);
		  
		  console.log("%%%%查看自定义指令v-color本身的一些属性%%%%");
		  el.style.backgroundColor = binding.value; 
		  console.log(binding.name+","+binding.value+","+binding.expression+","+binding.arg);
		})
		Vue.component("my-card",{
			template:'<div ref="card" v-on:click="toclick" v-color="obj[0].color0">12345678</div>',
			props:['obj'],
			methods:{
				toclick: function(){
					console.log("%%%%拿到props数据%%%%%");
					console.log(this.obj[0].color0);
					console.log("%%%%拿到虚拟dom%%%%");
					console.log(this.$refs.card);
					console.log("%%%%拿到非prop传入的name的属性值%%%%%");
					console.log(this.$refs.card.getAttribute('name'));
				}
			} 
		})
		
		// Vue.directive('demo',{ 
		// 	bind: function(el,binding,vnode){ 
		// 		el.innerHTML = 
		// 		'name: ' + binding.name + '<br/>' +
		// 		'value: ' + binding.value + '<br/>' +
		// 		'expression: ' + binding.expression + '<br/>' +
		// 		'arg: ' + binding.arg + '<br/>' +
		// 		'modifiers: ' + binding.modifiers + '<br/>' +
		// 		'vnode keys: ' + Object.keys(vnode).join(', ');
		// 		console.log("原来的vnode");
		// 		console.log(vnode);
		// 	},
		// 	update: function(el,binding,vnode){
		// 		el.style.backgroundColor = binding.value;
		// 		console.log("更新的vnode"+vnode);
		// 		console.log("背景色:"+binding.value); 
		// 	}
		// }) 
		new Vue({
			el: ".app",
			data: {
				colors:[
					{color0:'#0000ff'},
					{color1:'#00ff00'}
				]  
			}
		})
	</script>
</body>
</html>


Logo

前往低代码交流专区

更多推荐