为什么在vue3中不能使用直接导入自定义函数?导致“x 不是函数”错误

问题描述 投票:0回答:1

这让我发疯,我找到了一个解决方法。但我想了解为什么它不能直接工作。

本质上,我有我的主 vue 视图,以及我想要导入的自定义函数。

support.js

export function hello(what){
    return what
}

view.vue

<script>
   import { hello } from "@/support.js"
   export default{...}
</script>
<template>
   <h1> {{ hello("world") }} </h1>
</template>

这个设置不起作用,给我“_ctx.hello不是一个函数”错误。 (我也尝试过使用 this.hello() )

但是,如果我通过方法间接使用该函数,则有效。例如:

view.vue

<script>
   import { hello } from "@/support.js"
   export default{
   ...
      methods:{
         hello_local(what){
            return hello(what)
         }
      }
   }
</script>
<template>
   <h1> {{ hello_local("world") }} </h1>
</template>

然后就会产生预期的结果。

我确信对此有一个非常简单的解释,但我却无法理解。谁能告诉我为什么直接使用导入的函数不起作用?

javascript vuejs3
1个回答
0
投票

基本上,.vue 文件不是普通的 .js 文件,而是“vue 模板语言”文件。为了在浏览器中运行 vue 应用程序,您首先应该将其编译为常规 JavaScript。为了让编译器更简单,你应该遵循“vue 模板语言”规则

© www.soinside.com 2019 - 2024. All rights reserved.