我的main.js包含import "mathjs";并且似乎在 main.js 中作業正常
console.log(median(5,4,6,1));
> 4.5
median()但是在 main.js 之外不可用,即在組件中。閱讀此答案后,我認為簡單的匯入應該足以在整個 vue 應用程式中實作全域可用性?
uj5u.com熱心網友回復:
在 main.js 中匯入 all asmath然后將其添加為全域屬性:
import * as math from 'mathjs'
const app=createApp({....})
app.config.globalProperties.$math =math
然后在任何組件中你都可以像這樣使用它 this.$math.theFunctionName
uj5u.com熱心網友回復:
通常,當您使用現代模塊或像 webpack 這樣的打包器時,您必須在要使用它的每個模塊(思考檔案)中匯入 mathjs。
在 vue 背景關系中經常做的是使用插件將庫添加到 Vue 背景關系本身。
見https://v3.vuejs.org/guide/plugins.html#writing-a-plugin
所以這應該很簡單:
const mathjsPlugin = {
install(app){
app.config.globalProperties.$mathjs = mathjs;
}
}
const app = createApp(...);
app.use(mathjsPlugin);
// inside of a component
export default {
created(){
console.log(this.$mathjs....);
}
}
我個人認為顯式匯入是一種更簡潔的方法,但是如果在大多陣列件中使用 mathjs,則這種方法是有意義的
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/338425.html
