Vue中在setup下如何使用自定義指令
如何在setup下使用自定義指令
1. 局部的自定義指令
html中 v-img-rotote為自定義指令
<div class="card-item"> <div class="img"> <img v-img-rotote src="~@/assets/images/funny.png" /> </div> <div class="text-title lineEllipsisOne">小火車(chē)況且況且</div> </div>
在setup下面直接引用就行
- 方式一:是在該組件下直接寫(xiě)好指定代碼
<script lang="ts" setup> const vImgRotote = { beforeMount(el: HTMLElement) { el.onmouseover = () => { el.style.transform = 'rotate(-360deg)' el.style.transition = 'all 0.5s' } el.onmouseleave = () => { el.style.transform = 'rotate(0)' } } } </script>
- 方式二:是在固定文件夾下編寫(xiě)好了指令代碼, 然后直接引用即可, 前提是代碼不能出錯(cuò)的喲
<script lang="ts" setup> import vImgRotote from '@/directives/imgRotote' </script>
小提示???: 如果這個(gè)時(shí)候安裝了vscode中的Volar插件, 定義的代碼就會(huì)高亮顯示
2. 全局注冊(cè)自定義指令
全局和局部的自定義只是引用方式不同, 這里只是代表個(gè)人的寫(xiě)法, 小伙伴要有更好的可以直接忽視老夫的
在 src/directives中添加一個(gè)index.ts文件, 用來(lái)注冊(cè)所有的需要全局導(dǎo)入的自定義指令
index.ts的文件內(nèi)容, permission 是用來(lái)提示可以直接使用鏈?zhǔn)骄幊痰膶?xiě)法注冊(cè)其他的全局自定義指令
/** 用來(lái)到處全局的 自定義指令 */ import type { App } from 'vue' import permission from './permission' import imgRotote from './imgRotote' export default (app: App) => { app.directive('img-rotote', imgRotote).directive('permission', permission) }
然后將src/directives中的index.ts導(dǎo)入到main.ts中, 用來(lái)全局注冊(cè), 最后將app傳入, 用來(lái)注冊(cè)全局的自定義指令
import { createApp } from 'vue' import ElementPlus from 'element-plus' import 'element-plus/dist/index.css' // 基于斷點(diǎn)的隱藏類(lèi) Element 額外提供了一系列類(lèi)名,用于在某些條件下隱藏元素 import App from './App.vue' import router from './router' import { store, key } from './store' /** 注冊(cè)全局的 自定義指令 */ import globalDirectives from '@/directives' const app = createApp(App) app.use(store, key).use(router).use(ElementPlus).mount('#app') globalDirectives(app)
直接在代碼中引用即可
<div class="card-item"> <div class="img"> <img v-img-rotote src="~@/assets/images/funny.png" /> </div> <div class="text-title lineEllipsisOne">小火車(chē)況且況且</div> </div>
3. 簡(jiǎn)單的效果圖
4. 千萬(wàn)要注意
注冊(cè)自定義指令時(shí), 定義的name指令名稱(chēng)在使用的時(shí)候,不要寫(xiě)錯(cuò)了, 這里注冊(cè)的全局和局部的自定義指令名稱(chēng)都是img-rotote, 所以在html中使用時(shí)需要v-img-rotote,
如下所示:
<img v-img-rotote src="~@/assets/images/funny.png" />
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue使用ajax(axios)請(qǐng)求后臺(tái)數(shù)據(jù)的方法教程
在vue中經(jīng)常會(huì)用到數(shù)據(jù)請(qǐng)求,下面這篇文章主要給大家介紹了關(guān)于Vue使用ajax(axios)請(qǐng)求后臺(tái)數(shù)據(jù)的方法教程,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-11-11vue項(xiàng)目中如何配置eslint和prettier
這篇文章主要介紹了vue項(xiàng)目中如何配置eslint和prettier問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03vue+iview/elementUi實(shí)現(xiàn)城市多選
這篇文章主要介紹了vue+iview/elementUi實(shí)現(xiàn)城市多選,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03