Vue插件
vue
通常我们向Vue全局添加一些功能时,会采用插件的模式,它有两种编写方式
对象类型:一个对象,但是必须包含一个 install 的函数,该函数会在安装插件时执行;
函数类型:一个function,这个函数会在安装插件时自动执行;
插件可以完成的功能没有限制,比如下面的几种都是可以的:
1.添加全局方法或者 property,通过把它们添加到 config.globalProperties 上实现;
2.添加全局资源:指令/过滤器/过渡等;
3.通过全局 mixin 来添加一些组件选项
代码演示:
通过插件设置全局属性
对象类型:
main.js
import {
createApp
} from 'vue';
import router from './router';
import pluginObject from './02_plugins/plugins/plugins_object.js';
// import pluginFunction from './02_plugins/plugins/plugins_function';
import App from './02_plugins/App.vue';
const app = createApp(App);
app.use(router);
app.use(pluginObject);
// app.use(pluginFunction);
app.mount('#app');
plugins_object.js
export default {
install(app, options) {
app.config.globalProperties.$name = "trs";
}
};
App.vue
<template>
<div>plugins</div>
</template>
<script>
import { onMounted, getCurrentInstance } from "vue";
export default {
setup() {
//vue3中取值 顶层写法也一样
onMounted(() => {
const instance = getCurrentInstance();
console.log(
"instance.appContext " +
instance.appContext.config.globalProperties.$name
);
});
return {};
},
mounted() {
// vue2中取值
console.log("name", this.$name);
},
};
</script>
<style scoped></style>
函数类型
plugins_function.js
export default function (app, options) {
app.config.globalProperties.$name = "trs";
}
通过插件全局添加指令
plugins_function.js
import dayjs from 'dayjs';
export default function (app, options) {
app.config.globalProperties.$name = "trs";
app.directive("format-time", {
created(el, bindings) {
bindings.formatString = "YYYY-MM-DD HH:mm:ss";
if (bindings.value) {
bindings.formatString = bindings.value;
}
},
mounted(el, bindings) {
const textContent = el.textContent;
let timestamp = parseInt(textContent);
if (textContent.length === 10) {
timestamp = timestamp * 1000;
}
console.log("timestamp", timestamp);
el.textContent = dayjs(timestamp).format(bindings.formatString);
}
});
}
App.vue
<template>
<div>plugins</div>
<h2 v-format-time="`YYYY/MM/DD`">{{ timestamp }}</h2>
<h2 v-format-time>{{ timestamp }}</h2>
</template>
<!-- <script setup> -->
<script>
import { onMounted, getCurrentInstance } from "vue";
export default {
setup() {
const timestamp = 1624452193;
onMounted(() => {
const instance = getCurrentInstance();
console.log(
"instance.appContext " +
instance.appContext.config.globalProperties.$name
);
});
return {
timestamp,
};
},
mounted() {
// vue2中取值
console.log("name", this.$name);
},
};
</script>
<style scoped></style>