vue---自定义指令

一、定义语法:

(1).局部指令:

new Vue({directives:{指令名:配置对象}}) 或 new Vue({directives{指令名:回调函数}})

(2).全局指令:

Vue.directive(指令名,配置对象) 或 Vue.directive(指令名,回调函数)

二、配置对象中常用的3个回调:

(1).bind:指令与元素成功绑定时调用。

(2).inserted:指令所在元素被插入页面时调用。

(3).update:指令所在模板结构被重新解析时调用。

三、备注:

1.指令定义时不加v-,但使用时要加v-;

2.指令名如果是多个单词,要使用kebab-case命名方式,不要用camelCase命名。

javascript 复制代码
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>自定义指令</title>
		<script type="text/javascript" src="../js/vue.js"></script>
	</head>
	<body>
		<div id="root">
			<h2>{{name}}</h2>
			<h2>当前的n值是:<span v-text="n"></span> </h2>
			<!-- <h2>放大10倍后的n值是:<span v-big-number="n"></span> </h2> -->
			<h2>放大10倍后的n值是:<span v-big="n"></span> </h2>
			<button @click="n++">点我n+1</button>
			<hr/>
			<input type="text" v-fbind:value="n">
		</div>
	</body>
	
	<script type="text/javascript">
		Vue.config.productionTip = false

		//定义全局指令
		/* Vue.directive('fbind',{
			//指令与元素成功绑定时(一上来)
			bind(element,binding){
				element.value = binding.value
			},
			//指令所在元素被插入页面时
			inserted(element,binding){
				element.focus()
			},
			//指令所在的模板被重新解析时
			update(element,binding){
				element.value = binding.value
			}
		}) */

		new Vue({
			el:'#root',
			data:{
				name:'xiaoming',
				n:1
			},
			directives:{
				//big函数何时会被调用?1.指令与元素成功绑定时(一上来)。2.指令所在的模板被重新解析时。
				/* 'big-number'(element,binding){
					// console.log('big')
					element.innerText = binding.value * 10
				}, */
				big(element,binding){
					console.log('big',this) //注意此处的this是window
					// console.log('big')
					element.innerText = binding.value * 10
				},
				fbind:{
					//指令与元素成功绑定时(一上来)
					bind(element,binding){
						element.value = binding.value
					},
					//指令所在元素被插入页面时
					inserted(element,binding){
						element.focus()
					},
					//指令所在的模板被重新解析时
					update(element,binding){
						element.value = binding.value
					}
				}
			}
		})
		
	</script>
</html>
相关推荐
weixin199701080168 分钟前
《得物商品详情页前端性能优化实战》
前端·性能优化
帮我吧智能服务平台15 分钟前
装备制造企业售后服务数字化:从成本中心到利润中心背景
java·前端·制造
qq_3680196617 分钟前
用 react 的react-syntax-highlighter 实现语法高亮、行号与多行错误行高亮
前端·react.js·前端框架
lbh17 分钟前
从LLM到Agent的核心概念
前端·openai·ai编程
-Da-32 分钟前
【操作系统学习日记】并发编程中的竞态条件与同步机制:互斥锁与信号量
java·服务器·javascript·数据库·系统架构
Irene199134 分钟前
JavaScript脚本加载的两种方式:defer/async 的区别
前端·javascript·php
天若有情67339 分钟前
开篇必看:零基础吃透前端,别再盲目死记硬背了
前端
RulerMike1 小时前
three 实现简单机械臂逆运动
前端·ai编程·three.js
darkb1rd1 小时前
从“会聊天”到“会搭页面”:一次 TinyEngine + MCP 的前端智能化实战思路
前端
社恐的下水道蟑螂1 小时前
从奶茶店彻底搞懂 SSR!从零到拿捏服务端渲染,看完面试吹牛逼不卡壳
前端·react.js·性能优化