vuepress引入vue-qr组件后build报错navigator is not defined问题
最近博客中集成了vue-qr组件用于生成访问的二维码,记下vuepress引入外部组件后build报错问题的解决方法。
组件安装
npm install vue-qr
自定义组件代码
Qrcode.vue
<template><div class="vue-qrcode-box"><vue-qr :text="qrUrl" :size="114" :margin="5"></vue-qr></div></template><script>import vueQr from 'vue-qr'export default {name: 'qr-code',components: {vueQr},data() {return {qrUrl: ''}},mounted: function() {const that = thissetTimeout(() => {that.qrUrl = location.origin + that.$route.path}, 0)},watch: {$route(to, from) {if (from.path != to.path) {this.qrUrl = location.origin + this.$route.path}}},methods: {},created() {}}</script><style scoped>.vue-qrcode-box img {width: 100%;}</style>
组件引用
如果直接引入会报如下错误
原因:所有的页面在生成静态 HTML 时都需要通过 Node.js 服务端渲染,所有的 Vue 相关代码都应当遵循编写通用代码的要求。要确保只在
beforeMount或者mounted访问浏览器 / DOM 的 API。
如果一些组件或库在导入时就试图访问浏览器 API ,需要在合适的生命周期钩子中动态导入。
这里引用的 vue-qr 应该是使用了 navigator 的 API,所以就选择在单页的mounted里动态引入的方式来解决构建时的报错问题:
<template><component v-if="qrcode" :is="qrcode"></component></template><script>export default {data() {return {qrcode: null}},mounted () {import('./Qrcode').then(module => {this.qrcode = module.default})}}</script>
效果
参考资料
浏览器的 API 访问限制:https://vuepress.vuejs.org/zh/guide/using-vue.html#%E6%B5%8F%E8%A7%88%E5%99%A8%E7%9A%84-api-%E8%AE%BF%E9%97%AE%E9%99%90%E5%88%B6
编写通用代码的要求:https://ssr.vuejs.org/zh/guide/universal.html
觉得这篇文章有帮助?请转发给更多人
关注 极客之路 加星标,每天进步一点点
