【发布时间】:2021-05-02 11:36:49
【问题描述】:
我正在尝试在我的 Nuxt 应用程序中使用 format-unicorn npm 包。但是在我的 Vue 页面中导入它后,我收到以下错误:
Client: Missing stack frames
Server: [Vue warn]: Error in render: "TypeError: this.currencyFormat.formatUnicorn is not a function"
初步方法
以下方法应该根据plugins documentation工作:
在不安装模块的情况下使用
package的另一种方法是在<script>标签中直接导入package。
// Product.vue
<template>
<div class="product">
<p>Price: {{ localizedPrice }}</p>
</div>
</template>
<script>
require('format-unicorn')
export default {
data() {
return {
currencyFormat: '{c}{p}',
currency: '$',
price: 12.99
}
},
computed: {
localizedPrice: {
get() {
return this.currencyFormat.formatUnicorn({c: this.currency, p:this.price})
}
}
}
}
</script>
不幸的是,这种方法给了我一个错误:
Missing stack frames(没有其他有用的信息)。
在节点控制台中:[Vue warn]: Error in render: "TypeError: this.currencyFormat.formatUnicorn is not a function"
但奇怪的是,如果我用Nuxtlink 在那里导航,这个页面实际上打开时没有任何错误。但是一旦我点击刷新,错误仍然存在。
利用插件方法
通过在plugins 目录中创建format-unicorn.js 文件,我仍然遇到同样的错误:
//// plugins/format-unicorn.js
require('format-unicorn');
//// nuxt.config.js
// ...
plugins: [
'~/plugins/format-unicorn.js'
// applying mode: 'client' or 'server' doesn't help as well
],
// ...
朴素插件方法
我想知道它是否能正常工作,所以我只是将包 repo 中的代码粘贴到那里(它工作):
//// plugins/format-unicorn.js
String.prototype.formatUnicorn = function () {
let str = this.toString()
if (arguments.length) {
const type = typeof arguments[0]
const args = type === 'string' || type === 'number' ? Array.prototype.slice.call(arguments) : arguments[0]
for (const arg in args) str = str.replace(new RegExp(`\\{${arg}\\}`, 'gi'), args[arg])
}
return str
}
//// nuxt.config.js
// ...
plugins: [
'~/plugins/format-unicorn.js'
],
// ...
结论
此时您可能已经意识到我对幼稚的方法并不满意,因为我想在将来使用 3rd 方包扩展我的应用程序。我的问题是我做错了什么?尝试从 Nuxt 插件扩展原型有什么特别之处吗?或者我只是遗漏了一些东西?
【问题讨论】:
标签: javascript vue.js npm plugins nuxt.js