vue3自定义v-loading指令directives
vue3自定义v-loading指令directives1.在项目的src下创建一个directives文件夹写相应的指令2.比如自定义全局的v-loading 在文件下创建loading<template><div class="loading-container"><Loading size="300" /></div></template
·
vue3自定义v-loading指令directives
1.在项目的src下创建一个directives文件夹写相应的指令
2.比如自定义全局的v-loading 在文件下创建loading
<template>
<div class="loading-container">
<Loading size="300" />
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { Loading } from 'vant';
export default defineComponent({
components:{
Loading
},
setup() {
},
});
</script>
<style lang="scss" scoped>
.loading-container{
text-align: center;
width: 10.8rem;
position: absolute;
top: 50%;
z-index: 66;
}
</style>
3.相应的js代码directives/loading/index.ts
import {createApp, Directive } from 'vue';
import Loading from './index.vue';
export const loading: Directive = {
mounted(el,binding){
const app = createApp(Loading);
const instance = app.mount(document.createElement('div'));
el.instance = instance;
if (binding.value) {
appendEl(el);
}
},
updated(el,binding) {
if (binding.value !== binding.oldValue) {
binding.value ? appendEl(el) : removeEl(el);
}
},
};
const appendEl = (el) =>{
el.appendChild(el.instance.$el);
};
const removeEl = (el) =>{
el.removeChild(el.instance.$el);
};
4.在directives/index.ts中导出
5.在main.ts中全局引用
import * as directives from '@/directives';
Object.keys(directives).forEach(key => {
app.directive(key, (directives as { [key: string ]: Directive })[key]);
});
最后:在相应的页面中使用
更多推荐
已为社区贡献4条内容
所有评论(0)