国产精品天干天干,亚洲毛片在线,日韩gay小鲜肉啪啪18禁,女同Gay自慰喷水

歡迎光臨散文網 會員登陸 & 注冊

vue3自定義指令的使用

2021-07-31 22:39 作者:忘魂兒  | 我要投稿


## 自定義指令
##### 在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自定義指令的使用的評論 (共 條)

分享到微博請遵守國家法律
即墨市| 曲阜市| 秦安县| 洪江市| 广安市| 神池县| 忻州市| 安徽省| 富顺县| 宣武区| 天门市| 临夏县| 神池县| 哈密市| 青阳县| 那坡县| 浮山县| 广灵县| 奉化市| 文成县| 廉江市| 灌南县| 临夏县| 乐陵市| 宜昌市| 义乌市| 祁连县| 库尔勒市| 渑池县| 大名县| 南漳县| 吉木乃县| 杭锦旗| 浮山县| 突泉县| 江陵县| 沈丘县| 手机| 东至县| 溧阳市| 清河县|