目录
Vue3定义全局函数和变量
因为vue3没有prototype属性所以要使用 app.config.globalProperties 来在全局绑定函数或者变量
vue2的用法
Vue.prototype.$http = () => {}
vue3的用法
在main.ts内
import { createApp } from 'vue'
import App from './App.vue'
import "animate.css"
const app = createApp(App)
type Filter = {
format: (str:string)=>string
}
declare module 'vue' {
export interface ComponentCustomProperties {
$filters: Filter,
$api: string
}
}
app.config.globalProperties.$api = "https://api.themoviedb.org/3"
app.config.globalProperties.$filtter = {
format: (str:string):string=> {
return '加上' + str
}
}
app.mount('#app')
需要声明文件declare module 在组件中使用时,才会有提示
在组件中使用,模板中直接插值语法,setup中需要使用getCurrentInstance获取当前实例,然后通过当前实例的props属性找到
<script setup lang="ts">
import { ref } from 'vue';
import {getCurrentInstance} from "vue";
const instance = getCurrentInstance();
const text = ref('');
function changeInput() {
text.value = instance?.proxy?.$filters.format(text.value) as string;
}
</script>
<template>
<div class="context">
<p>{
{$api}}</p>
<input type="text" v-model="text" @input="changeInput">
{
{text}}
</div>
</template>
<style scoped>
.image img{
width: 300px;
}
</style>
vue3编写插件
在使用 createApp()
初始化 Vue 应用程序后,你可以通过调用 use()
方法将插件添加到你的应用程序中。
实现一个Loading
app.vue
<script setup lang="ts">
import {getCurrentInstance} from "vue";
const instance = getCurrentInstance()
instance?.proxy?.$loading.sho