我有一个多域页面,它应该以不同方式显示每个域的组件。因此我喜欢有一个“全局”函数,我可以在模板内的“v-if”语句中使用它
我遵循了使用插件创建全局对象的建议 how-to-define-a-global-method-accessible-to-all-components .不幸的是我此时不知道如何获取主机名/域名,因为js对象“window”似乎未定义?
知道我如何才能最好地实现这一点吗?谢谢
我的插件“global.js”=> 返回“window”对象未定义的错误
const cmsURLBuilder = {
isDomain(domain) {
return this.window.location.hostname.includes(domain);
},
}
export default ({app}, inject) => {
inject('cmsURLBuilder', cmsURLBuilder);
}
在我的模板中使用这个全局对象
<template>
<div>
<iframe v-if="$cmsURLBuilder.isDomain('xxx')" id="frame-xxx" src="https://xxxx/..." />
...
</div>
</template>
最佳答案
将您的插件模式设置为客户端。
plugins: [
{ src: '~/plugins/myplugin.js', mode: 'client' }
]
或者将你的调用包装到 window 对象,
if (process.client) {
console.log('window.location', window.location)
}
关于javascript - Vue + Nuxt JS - 如何在 "global"函数中获取主机名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59469955/