vue3自定義指令的使用
## 自定義指令
##### 在Vue的模板語法中我們學習過各種各樣的指令:v-show、v-for、v-model等等,除了使用這些指令之外,Vue也允許我們來自定義自己的指令
### 自定義指令分為兩種:自定義局部指令和自定義全局指令
#### 自定義局部指令:組件中通過 directives 選項,只能在當前組件中使用
export default {
? ?directives:{
? ? ? ?focus:{
? ? ? ? ? ?mounted(el){
? ? ? ? ? ? ? ?el.focus(); //聚焦函數(shù)
? ? ? ? ? ?}
? ? ? ?}
? ?}
}
//在當前組件內均可使用v-focus
<input v-focus />
##### 相比之下,如果我們不用局部自定義指令,在該組件內部
import {ref,onMounted} from 'vue'
setup(){
? ?const in =ref(null)
? ?onMounted(()=>{
? ? ? ?in.value.focus()
? ?})
? ?return {
? ? ? ?in
? ?}
}
#### 自定義全局指令:全局的自定義指令可以讓我們在任何地方直接使用,在App.vue內書寫
app.directive("focus",{
? ?mounted(el){
? ? ?el.focus()
? ?}
})
### 指令的生命周期
#### created:在綁定元素的 attribute 或事件監(jiān)聽器被應用之前調用
#### beforeMount:當指令第一次綁定到元素并且在掛載父組件之前調用
#### mounted:在綁定元素的父組件被掛載后調用
#### beforeUpdate:在更新包含組件的 VNode 之前調用
#### updated:在包含組件的 VNode 及其子組件的 VNode 更新后調用
#### beforeUnmount:在卸載綁定元素的父組件之前調用
#### unmounted:當指令與元素解除綁定且父組件已卸載時,只調用一次
### 指令的參數(shù)和修飾符
<button v-focus:info.a.b="{name:'xwl', age:18}"></button>
##### info是參數(shù)的名稱;a,b是修飾符的名稱,后面是傳入的具體的值.
##### 在生命周期中,我們可以通過 bindings 獲取到對應參數(shù)的具體內容
### 小試牛刀:自定義時間戳指令 v-format-time
#### 我們先創(chuàng)建入口,接收app
import registerFormatTime from './format-time';//轉換函數(shù)
export default function registerDirectives(app) {
? ?//用registerDirectives來接收app
? ?registerFormatTime(app);//轉換函數(shù)調用,并向其傳入app
}
format-time.js中
import dayjs from 'dayjs'; //導入時間內置函數(shù)
export default function(app){
? ?let formatString="YYYY-MM-DD HH:mm:ss";//默認接收這種格式
? ?app.directive("format-time",{
? ? ? ?created(el,bindings){
? ? ? ? ? ?if(bindings.value){
? ? ? ? ? ? ? ?formatString=bindings.value;
? ? ? ? ? ?}
? ? ? ?},
? ? ? ?mounted(el,bindings){
? ? ? ? ? ?log("format mounted");
? ? ? ? ? ?const testContent=el.textContent;
? ? ? ? ? ?let timestamp=parseInt(textContent);
? ? ? ? ? ?if(textContent.length===10){
? ? ? ? ? ? ? ?timestamp=timestamp*1000
? ? ? ? ? ?}
? ? ? ? ? ?el.textContent=dayjs(timestamp).format(formatString);
? ? ? ?}
? ?})
}
main.js中
import registerDirectives from './directives'
registerDirectives(app);



標簽:
vue3自定義指令的使用的評論 (共 條)
