問(wèn)題
我是看網(wǎng)上大部分說(shuō)的Vue2.x的 Vue.prototype 應(yīng)該換成以下寫(xiě)法
import toast from './scripts/toast';
import { createApp } from 'vue'
import App from './App.vue'
export default {
version: '1.0.0',
author: 'lzh',
install: function (Vue) {
const app = createApp(App);
app.config.globalProperties.$toast = toast;
}
}
import { getCurrentInstance, onMounted } from "vue";
export default {
setup( ) {
const { ctx } = getCurrentInstance(); //獲取上下文實(shí)例
onMounted(() => {
console.log(ctx, "ctx");
ctx.$toast('測(cè)試');
});
},
};
但是結(jié)果并不能使用
報(bào)錯(cuò)信息
$toast is undefined
于是我想起了Vue.use默認(rèn)執(zhí)行插件的install方法并傳入Vue當(dāng)前實(shí)例
所以我打印了一下Vue
打印結(jié)果
發(fā)現(xiàn)了端倪
然后將代碼改成這樣就可以啦
import toast from './scripts/toast';
export default {
version: '1.0.0',
author: 'lzh',
install: function (Vue) {
// toast Fn
Vue.config.globalProperties.$Toast = toast;
}
}
注意:使用getCurrentInstance()時(shí)候要注意盡量別使用里邊的ctx屬性 打包后容易出錯(cuò)饿悬,尤大大推薦使用內(nèi)部的 proxy
const { proxy } = getCurrentInstance();
proxy.$toast('測(cè)試成功');