Vue3_13(自定义指令 | Teleport | 插件)
自定义指令 | Vue.js https://v3.cn.vuejs.org/guide/migration/custom-directives.html#_3-x-%E8%AF%AD%E6%B3%95
注意:在Vue中,代码的复用和抽象主要还是通过组件;需要对DOM元素进行底层操作,就会用到自定义指令
自定义局部指令:组件中通过 directives 选项,只能在当前组件中使用;
自定义全局指令:app的 directive 方法,可以在任意组件中被使用;
#局部指令
<template>
<div>
<input type="text" v-focus>
</div>
</template>
<script>
export default {
// 局部指令
directives: {
focus: {
mounted(el, bindings, vnode, preVnode) {
console.log("focus mounted");
el.focus();
}
}
}
}
</script>
#全局指令
app.directive("focus", {
mounted(el, bindings, vnode, preVnode) {
el.focus();
}
})
指令的生命周期
created:在绑定元素的 attribute 或事件监听器被应用之前调用;
beforeMount:当指令第一次绑定到元素并且在挂载父组件之前调用;
mounted:在绑定元素的父组件被挂载后调用;
beforeUpdate:在更新包含组件的 VNode 之前调用;
updated:在包含组件的 VNode 及其子组件的 VNode 更新后调用;
beforeUnmount:在卸载绑定元素的父组件之前调用;
unmounted:当指令与元素解除绑定且父组件已卸载时,只调用一次;
指令的参数和修饰符
通过 bindings 获取到对应的内容
<template>
<div>
<button v-if="counter < 2" v-gog.aaaa.bbbb="'coderwhy'" @click="increment">当前计数: {{counter}}</button>
</div>
</template>
<script>
import { ref } from "vue";
export default {
// 局部指令
directives: {
gog: {
created(el, bindings, vnode, preVnode) {
console.log("created", el, bindings, vnode, preVnode);
console.log(bindings.value);
console.log(bindings.modifiers);
},
beforeMount() {
console.log(" beforeMount");
},
mounted() {
console.log("mounted");
},
beforeUpdate() {
console.log("beforeUpdate");
},
updated() {
console.log("updated");
},
beforeUnmount() {
console.log("beforeUnmount");
},
unmounted() {
console.log("unmounted");
}
}
},
setup() {
const counter = ref(0);
const increment = () => counter.value++;
return {
counter,
increment
}
}
}
</script>
Teleport | Vue.js https://v3.cn.vuejs.org/guide/teleport.html#teleport
Teleport翻译过来是心灵传输、远距离运输的意思;是一个Vue提供的内置组件,类似于react的Portals。适合做消息弹窗
属性 to:指定将其中的内容移动到的目标元素,可以使用选择器;
属性 disabled:是否禁用 teleport 的功能;
#把teleport 内dom 挂载到<div id="aaa"></div>
<teleport to="#aaa">
<h2>当前计数</h2>
<button>+1</button>
<hello-world></hello-world>
</teleport>
Vue插件 | Vue.js https://v3.cn.vuejs.org/guide/plugins.html#%E6%8F%92%E4%BB%B6
两种编写方式:
对象类型:一个对象,但是必须包含一个 install 的函数,该函数会在安装插件时执行;
函数类型:一个function,这个函数会在安装插件时自动执行;
功能示范:
添加全局方法或者 property,通过把它们添加到 config.globalProperties 上实现;
添加全局资源:指令/过滤器/过渡等;
通过全局 mixin 来添加一些组件选项;
一个库,提供自己的 API,同时提供上面提到的一个或多个功能;
#plugins_object.js
export default {
install(app) {
app.config.globalProperties.$name = "coderwhy"
}
}
#plugins_function.js
export default function(app) {
console.log(app);
}

浙公网安备 33010602011771号