[Vue.js] Usage of custom instructions

The following lists the usage of custom commands and the usage of custom commands with parameters.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>自定义指令</title>
		<script src="../js/vue.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<div id="app">
			<!--自定义指令:v-自定义名称-->
			<input type="text" v-focus/>
			
			<!--带参数的自定义指令:v-自定义名称=""-->
			<input type="text" v-color="msg" />
		</div>
		<script type="text/javascript">
			//自定义指令(指令名称,对象)
			Vue.directive("focus",{
				//inserted:元素插入父节点时调用
				inserted:function(el){
					//el表示指令所绑定的元素
					el.focus();
				}
			});
			
			/*带参数的自定义指令*/
			Vue.directive("color",{
				//bind:该元素绑定指令时仅调用一次,用于初始化
				bind:function(el,binding){ 
					//binding是一个对象,可以用其他的表示,包含name属性:获取指令名;value属性:指令的绑定值等
					//改变元素背景色
					el.style.backgroundColor=binding.value.color;
				}
			});
			
			var vm=new Vue({
				el:"#app",
				data:{
					msg:{
						color:"red"
					}
				}
			});
		</script>
	</body>
</html>

Note: You must first introduce the vue.js file.

Published 19 original articles · praised 20 · visits 487

Guess you like

Origin blog.csdn.net/Handsome_gir/article/details/105605760