自定义方法
子组件
<template>
<div class="divBgc">
子组件
</div>
</template>
<script setup lang="ts" name="Father">
</script>
<style scoped lang="less">
.divBgc {
width: 200px;
height: 200px;
background-color: pink;
}
</style>
父组件
<template>
<div>
<Son v-DIV="{ color: 'red' }" v-Color="{ background: 'red' }"></Son>
</div>
</template>
<script setup lang="ts">
import Son from './components/Son1.vue'
import { Directive, DirectiveBinding } from 'vue'
// DirectiveBinding的类型
type Dir = {
color: string
background: string
}
// 自定义指令
const vDIV: Directive = {
mounted(el: HTMLElement, dir: DirectiveBinding<Dir>) {
el.style.color = dir.value.color
},
updated() {
},
unmounted() {
}
}
// 当你不关心除了 mounted 和 updated (且这两个钩子行为相同) 以外的其他钩子,可以函数简写
const vColor: Directive = (el: HTMLElement, dir: DirectiveBinding<Dir>) => {
el.style.background = dir.value.background
}
</script>
<style scoped lang="less">
</style>
使用 VueUse 中的 Hooks
安装 vueuse
npm i @vueuse/core
看文档直接使用就行
自定义插件
1.创建Loading文件夹创建 index.ts 和 index.vue
2.在main.ts中引入并注册插件
import { createApp } from "vue";
import "./style.css";
import App from "./App.vue";
const app = createApp(App);
// 引入并注册自定义的Loading插件
import Loading from "./components/Loding";
app.use(Loading);
app.mount("#app");
3.index.vue文件
<template>
<div class="divBgc" v-if="flag">
loading......
</div>
</template>
<script setup lang="ts" name="Father">
import { ref } from 'vue';
const flag = ref(false)
const show = () => flag.value = true
const hide = () => flag.value = false
// 抛出方法
defineExpose({
flag,
show,
hide
})
</script>
<style scoped lang="less">
.divBgc {
width: 200px;
height: 200px;
background-color: pink;
}
</style>
4.index.ts 文件
// 引入 APP 类型
import type { App, VNode } from "vue";
// 引入 vue 文件
import Loading from "./index.vue";
// 引入 createVNode 底层函数和 render 挂载函数
import { createVNode, render } from "vue";
export default {
// 默认必须写
install(app: App) {
const Vnode: VNode = createVNode(Loading);
// 将Vnode挂载到body上(因为插件是全局的)
render(Vnode, document.body);
// 获取Loading插件暴露出来的东西
Vnode.component?.exposed;
// 将api挂载到全局
app.config.globalProperties.Loading = {
show: Vnode.component?.exposed?.show,
hide: Vnode.component?.exposed?.hide,
};
},
};
5.在App.vue 中使用Loading插件
<template>
<div>
</div>
</template>
<script setup lang="ts">
// 获取当前组件实例
import { getCurrentInstance } from 'vue';
const instance = getCurrentInstance()
// 调用挂载的方法
instance?.proxy?.Loading.show()
setTimeout(() => {
instance?.proxy?.Loading.hide()
}, 3000);
</script>
<style scoped lang="less">
</style>
注意:此时你会发现 .Loading 这里报错,原因是因为缺少 Loading 的类型,创建一个 Loading.d.ts 的声明文件,去声明一下 Loading 的类型就不会有报错了。
6.Loading.d.ts
export {};
type Loading = {
show: () => void;
hide: () => void;
};
declare module "@vue/runtime-core" {
export interface ComponentCustomProperties {
Loading: Loading;
}
}
此时你在任何组件中都可以使用该插件