vue17自定義指令(有引數,無引數)

徵鴻Sir發表於2020-10-14

vue內建指令不滿足需求

需求,當使用者開啟一個表單的時候,使用者不用點選第一個輸入框,而是直接獲取第一個輸入框的焦點

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			
		</style>
	</head>
	<body>
		<div id="app">
			<form>
				<div>
					<span>
						<input type="text"/>
						<input type="text" v-newname />
						<input type="text" v-newname1 = "msg" @keyup.enter="setcolor" />
					</span>
				</div>
			</form>
		</div>
		<script type="text/javascript" src="../js/vue.js"></script>
		<script type="text/javascript">
			/* 自定義指令-無引數 */
			Vue.directive('newname',{
				inserted:function(el){
					/* newName  新的指令名稱
					   el 指令所繫結的元素
					 */
					el.focus();//定義指令動作為 獲取焦點
				}
			});
			/* 自定義指令-有引數 */
			Vue.directive('newname1',{
				bind:function(el,binding){
					/* newName  新的指令名稱
					   el 指令所繫結的元素
					   binding 指令繫結的物件
					 */
					console.log(binding)
					el.style.backgroundColor = binding.value.color
				}
			});
			var vm = new Vue({
				el:'#app', 
				data:{
					uname:'',
					msg:{
						name:'張三',
						age:22,
						color:'red',
					}
				},
				methods:{
					setcolor:function(){
						console.log(event.target.value)
					}
				},
			});
		</script>
	</body>
</html>

效果圖
在這裡插入圖片描述

相關文章