当前位置: 首页 > news >正文

19 vue3之自定义指令Directive按钮鉴权

directive-自定义指令(属于破坏性更新)

Vue中有v-if,v-for,v-bind,v-show,v-model 等等一系列方便快捷的指令 今天一起来了解一下vue里提供的自定义指令

Vue3指令的钩子函数

  • created 元素初始化的时候
  • beforeMount 指令绑定到元素后调用 只调用一次
  • mounted 元素插入父级dom调用
  • beforeUpdate 元素被更新之前调用
  • update 这个周期方法被移除 改用updated
  • beforeUnmount 在元素被移除前调用
  • unmounted 指令被移除后调用 只调用一次

Vue2 指令的钩子函数

 bind inserted update componentUpdated unbind

在setup内定义局部指令

但这里有一个需要注意的限制:必须以 vNameOfDirective 的形式来命名本地自定义指令,以使得它们可以直接在模板中使用。

 父组件

<template>
<Av-move-directive.aa.cookie="{background: 'red',}"></A
</template><script setup lang="ts">
import {ref,reactive,Directive,DirectiveBinding,
} from "vue";
import A from "./components/twenty_one_A.vue";
let flag = ref<boolean>(true);
let color = ref<string>("");type Value = {//这样才会提示background,帮助我们做内型推导background: string;
};const vMoveDirective: Directive = {// 自定义指令必须以v开头 Directivecreated: () => {console.log("created初始化====>");},beforeMount(...args: Array<any>) {console.log("beforeMount初始化一次=======>");console.log("args==>", args); // 共有4个参数 1是组件的元素 2是dir 3.是虚拟Dom 4.是上一次更新的dom//获取到这些内容后在元素上做些操作},mounted(el: any, dir: DirectiveBinding<Value>) {el.style.background = dir.value.background;console.log("mounted初始化========>");},beforeUpdate() {console.log("beforeUpdate更新之前");},updated() {console.log("updated更新结束");},beforeUnmount(...args: Array<any>) {console.log(args);console.log("======>beforeUnmount卸载之前");},unmounted(...args: Array<any>) {console.log(args);console.log("======>unmounted卸载完成");},
};</script>

A组件

<template><div class="box">子组件</div>
</template><script setup lang="ts">
import { ref, reactive } from "vue";
</script><style lang="less" scoped>
.box {width: 100px;height: 100px;background: pink;
}
</style>

生命周期钩子参数详解

第一个 el  当前绑定的DOM 元素

第二个 binding

instance:使用指令的组件实例。
value:传递给指令的值。例如,在 v-my-directive="1 + 1" 中,该值为 2。
oldValue:先前的值,仅在 beforeUpdate 和 updated 中可用。无论值是否有更改都可用。
arg:传递给指令的参数(如果有的话)。例如在 v-my-directive:foo 中,arg 为 "foo"。
modifiers:包含修饰符(如果有的话) 的对象。例如在 v-my-directive.foo.bar 中,修饰符对象为 {foo: true,bar: true}。
dir:一个对象,在注册指令时作为参数传递。例如,在以下指令中


第三个 当前元素的虚拟DOM 也就是Vnode

第四个 prevNode 上一个虚拟节点,仅在 beforeUpdate 和 updated 钩子中可用

更新和卸载

 <!-- 卸载 --><!--  <Av-if="flag"v-move-directive="{ background: 'red' }"></A> --><!-- 更新 aa.cookie是随意写的自定义修饰符 --><!-- <Av-move-directive.aa.cookie="{background: 'red',flag: flag,}"></A> -->

函数简写

你可能想在 mounted 和 updated 时触发相同行为,而不关心其他的钩子函数。那么你可以通过将这个函数模式实现

<template><div><input v-model="value" type="text" /><A v-move="{ background: value }"></A></div>
</template><script setup lang='ts'>
import A from './components/A.vue'
import { ref, Directive, DirectiveBinding } from 'vue'
let value = ref<string>('')
type Dir = {background: string
}
const vMove: Directive = (el, binding: DirectiveBinding<Dir>) => {el.style.background = binding.value.background
}
</script><style>
</style>

 自定义指令-按钮鉴权案例

根据权限显示和隐藏对应的按钮

<template><h3>按钮鉴权案例</h3><div><button v-has-button="'shop:create'">新增</button><button v-has-button="'shop:edit'">编辑</button><button v-has-button="'shop:delete'">删除</button></div>
</template><script setup lang="ts">
import {ref,reactive,Directive,DirectiveBinding,
} from "vue";// 按钮鉴权localStorage.setItem("userId", "cookie1");//mock后台返回的数据
const permission = ["cookie1:shop:edit","cookie1:shop:create",// "cookie1:shop:delete",
];
const userId = localStorage.getItem("userId") as string;
const vHasButton: Directive<HTMLElement, string> = (el,bingding
) => {if (!permission.includes(userId + ":" + bingding.value)) {el.style.display = "none";}
};</script><style lang="less" scoped>
</style>
 效果图:

  自定义指令-图片懒加载案例

import.meta.globEager vite获取文件下的所有图片

// glob 懒加载 是import函数得方式 () => import('')
// globEager 静态加载 是import xxx from 'xxx'的方式

new IntersectionObserver判断元素是否在可视区内

<template><hr /><h3>图片懒加载</h3><div><div v-for="(item, index) in arr" :key="index"><imgheight="500":data-index="item"v-lazy="item"width="360"alt=""/></div></div>
</template><script setup lang="ts">
import {ref,reactive,Directive,DirectiveBinding,
} from "vue";// 图片懒加载
// glob 懒加载 是import函数得方式 () => import('')
// globEager 静态加载 是import xxx from 'xxx'的方式
const images: Record<string, { default: string }> =import.meta.globEager("./assets/images/*.*");
let arr = Object.values(images).map((v) => v.default);let vLazy: Directive<HTMLImageElement, string> = async (el,binding
) => {let url = await import("./assets/vue.svg");el.src = url.default;// new IntersectionObserver判断元素是否在可视区内let observer = new IntersectionObserver((entries) => {console.log(entries[0], el);if (entries[0].intersectionRatio > 0 &&entries[0].isIntersecting) {setTimeout(() => {el.src = binding.value;observer.unobserve(el);}, 2000); // 加了延迟方便查看效果}});observer.observe(el);
};</script><style lang="less" scoped>
</style>
效果图

 以上所有完整的示例代码

A组件都是同个文件

<template><h3>自定义指令</h3><button @click="flag = !flag">开关</button><!-- 卸载 --><!--  <Av-if="flag"v-move-directive="{ background: 'red' }"></A> --><!-- 更新 aa.cookie是随意写的自定义修饰符 --><!-- <Av-move-directive.aa.cookie="{background: 'red',flag: flag,}"></A> --><!--   <hr /><h3>自定义函数简写 /v-move1-directive.aaa.cookie代表属性和修饰符</h3><input type="text" v-model="color" /><Av-move1-directive.aaa.cookie="{ background: color }"></A> --><!-- <hr /><h3>按钮鉴权案例</h3><div><button v-has-button="'shop:create'">新增</button><button v-has-button="'shop:edit'">编辑</button><button v-has-button="'shop:delete'">删除</button></div> --><hr /><h3>图片懒加载</h3><div><div v-for="(item, index) in arr" :key="index"><imgheight="500":data-index="item"v-lazy="item"width="360"alt=""/></div></div><!--<hr /><h3>自定义指令案例移动盒子</h3><div v-move class="box"><div class="header">按住头部可以移动</div><div>内容</div></div> -->
</template><script setup lang="ts">
import {ref,reactive,Directive,DirectiveBinding,
} from "vue";
import A from "./components/twenty_one_A.vue";
let flag = ref<boolean>(true);
let color = ref<string>("");type Value = {//这样才会提示background,帮助我们做内型推导background: string;
};const vMoveDirective: Directive = {// 自定义指令必须以v开头 Directivecreated: () => {console.log("created初始化====>");},beforeMount(...args: Array<any>) {console.log("beforeMount初始化一次=======>");console.log("args==>", args); // 共有4个参数 1是组件的元素 2是dir 3.是虚拟Dom 4.是上一次更新的dom//获取到这些内容后在元素上做些操作},mounted(el: any, dir: DirectiveBinding<Value>) {el.style.background = dir.value.background;console.log("mounted初始化========>");},beforeUpdate() {console.log("beforeUpdate更新之前");},updated() {console.log("updated更新结束");},beforeUnmount(...args: Array<any>) {console.log(args);console.log("======>beforeUnmount卸载之前");},unmounted(...args: Array<any>) {console.log(args);console.log("======>unmounted卸载完成");},
};// 函数简写
type Dir = {background: string;
};const vMove1Directive: Directive = (el: HTMLElement, // 获取的是A组件的实例binding: DirectiveBinding<Dir> // 指令上的值
) => {el.style.background = binding.value.background;
};// 按钮鉴权localStorage.setItem("userId", "cookie1");//mock后台返回的数据
const permission = ["cookie1:shop:edit","cookie1:shop:create",// "cookie1:shop:delete",
];
const userId = localStorage.getItem("userId") as string;
const vHasButton: Directive<HTMLElement, string> = (el,bingding
) => {if (!permission.includes(userId + ":" + bingding.value)) {el.style.display = "none";}
};// 图片懒加载
// glob 懒加载 是import函数得方式 () => import('')
// globEager 静态加载 是import xxx from 'xxx'的方式
const images: Record<string, { default: string }> =import.meta.globEager("./assets/images/*.*");
let arr = Object.values(images).map((v) => v.default);let vLazy: Directive<HTMLImageElement, string> = async (el,binding
) => {let url = await import("./assets/vue.svg");el.src = url.default;// new IntersectionObserver判断元素是否在可视区内let observer = new IntersectionObserver((entries) => {console.log(entries[0], el);if (entries[0].intersectionRatio > 0 &&entries[0].isIntersecting) {setTimeout(() => {el.src = binding.value;observer.unobserve(el);}, 2000);}});observer.observe(el);
};// 自定义指令案例移动盒子
const vMove: Directive = {mounted(el: HTMLElement) {console.log(el.firstElementChild); // 获取父元素内的第一个节点console.log(el.lastElementChild); // 获取父元素内的最后一个节点let moveEl = el.firstElementChild as HTMLElement;const mouseDown = (e: MouseEvent) => {//鼠标点击物体那一刻相对于物体左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离console.log(e.clientX,e.clientY,"-----起始",el.offsetLeft);let X = e.clientX - el.offsetLeft;let Y = e.clientY - el.offsetTop;const move = (e: MouseEvent) => {el.style.left = e.clientX - X + "px";el.style.top = e.clientY - Y + "px";console.log(e.clientX, e.clientY, "---改变");};document.addEventListener("mousemove", move);document.addEventListener("mouseup", () => {document.removeEventListener("mousemove", move);});};moveEl.addEventListener("mousedown", mouseDown);},
};
</script><style lang="less" scoped>
</style>

20 vue3之自定义hooks-CSDN博客文章浏览阅读63次。Vue3 自定义Hook的作用主要用来处理复用代码逻辑的一些封装Vue3 的 hook函数 相当于 vue2 的 mixin, 不同在与hooks 是函数Vue3 的 hook函数 可以帮助我们提高代码的复用性, 让我们能在不同的组件中都利用 hooks 函数这个在vue2 就已经有一个东西是Mixinsmixins就是将这些多个相同的逻辑抽离出来,各个组件只需要引入mixins,就能实现一次写代码,多组件受益的效果。https://blog.csdn.net/qq_37550440/article/details/142548504?sharetype=blogdetail&sharerId=142548504&sharerefer=PC&sharesource=qq_37550440&spm=1011.2480.3001.8118

相关文章:

  • 在AI时代,程序员如何提升核心竞争力?
  • 本地电脑基于nginx的https单向认证和双向认证(自制证书+nginx配置)保姆级
  • Unix-like 系统中的文件所有权管理:使用 sudo chown -R 命令的详解与实践应用
  • Stable Diffusion绘画 | 插件-Deforum:动态视频生成
  • util-linux 和 dosfstools 开发 ,fdisk mkfs工具移植
  • New major version of npm available! 8.3.1 -> 10.8.3 报错
  • Trick : pair 的二分问题
  • 【RocketMQ】MQ与RocketMQ介绍
  • 国产化低功耗低延时广覆盖物联网无线通讯方案_LAKI模组
  • 【深度学习】深度卷积神经网络(AlexNet)
  • 在vue项目中禁用鼠标右键,选中
  • AI技术在爱奇艺视频搜索中的应用
  • linux从入门到精通--从基础学起,逐步提升,探索linux奥秘(六)
  • 数据结构-3.4.队列的基本概念
  • shell脚本使用==判断相等报错
  • docker python 配置
  • DOM的那些事
  • emacs初体验
  • ES6系统学习----从Apollo Client看解构赋值
  • express如何解决request entity too large问题
  • java架构面试锦集:开源框架+并发+数据结构+大企必备面试题
  • MySQL-事务管理(基础)
  • WebSocket使用
  • 百度贴吧爬虫node+vue baidu_tieba_crawler
  • 从零到一:用Phaser.js写意地开发小游戏(Chapter 3 - 加载游戏资源)
  • 大整数乘法-表格法
  • 聚类分析——Kmeans
  • 面试题:给你个id,去拿到name,多叉树遍历
  • 前端每日实战:70# 视频演示如何用纯 CSS 创作一只徘徊的果冻怪兽
  • 深度学习入门:10门免费线上课程推荐
  • 移动端唤起键盘时取消position:fixed定位
  • MyCAT水平分库
  • ​ssh-keyscan命令--Linux命令应用大词典729个命令解读
  • $(function(){})与(function($){....})(jQuery)的区别
  • (55)MOS管专题--->(10)MOS管的封装
  • (PySpark)RDD实验实战——取最大数出现的次数
  • (ZT)薛涌:谈贫说富
  • (安卓)跳转应用市场APP详情页的方式
  • (附程序)AD采集中的10种经典软件滤波程序优缺点分析
  • (附源码)ssm高校运动会管理系统 毕业设计 020419
  • (三分钟了解debug)SLAM研究方向-Debug总结
  • (实测可用)(3)Git的使用——RT Thread Stdio添加的软件包,github与gitee冲突造成无法上传文件到gitee
  • (四)TensorRT | 基于 GPU 端的 Python 推理
  • (一)使用IDEA创建Maven项目和Maven使用入门(配图详解)
  • (已解决)Bootstrap精美弹出框模态框modal,实现js向modal传递数据
  • (原創) 如何優化ThinkPad X61開機速度? (NB) (ThinkPad) (X61) (OS) (Windows)
  • (转)Spring4.2.5+Hibernate4.3.11+Struts1.3.8集成方案一
  • .NET Core 中的路径问题
  • .Net程序帮助文档制作
  • .NET牛人应该知道些什么(2):中级.NET开发人员
  • .NET之C#编程:懒汉模式的终结,单例模式的正确打开方式
  • .sh
  • /dev下添加设备节点的方法步骤(通过device_create)
  • [<事务专题>]
  • [2010-8-30]