首先vue2 插件的时候会暴露一个 install 方法,并通过全局方法 Vue.use() 使用插件。install 方法的第一个参数是 Vue 构造器,插件的方法就添加在 Vue 构造器的原型对象上。通过 new Vue() 实例化后,在组件中就能调用 this.$toas了。
而在Vue3中install 传入的不是Vue的构造器没有原型对象,Vue.prototype是undefined 所以没办法直接通过this调用
// 插件内容
export default {
install: (app: any, options: any) => {
console.log(options)
app.config.globalProperties.$toast = (name: any) => {
// 插件逻辑
}
}
}
// main.js
import { createApp } from 'vue';
import App from './App';
import toast from 'xxx/xxxx/toast'
const app = createApp(App)
app.use(toast).mount('#app')
// 需要调用插件的组件
export default defineComponent({
setup() {
const { proxy } = getCurrentInstance()
const toast = proxy.$toast
//使用
toast()
}
})
希望对你能有帮助