skip to Main Content

This drove me insane, and I figured out a workaround. But I want to understand why it does not work in a straight forward way.

Essentially, I have my main vue view, and a custom function I want to import.

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>

And this setup does not work, giving me the "_ctx.hello is not a function" error.
(I also tried using this.hello() )

What does work however is if I use the function indirectly, via methods. E.g.:

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>

Which then yields the expected results.

I am sure there is a very simple explanation for this, but it elludes me. Can anyone tell me why the direct use of the imported function does not work?

2

Answers


  1. Basically, a .vue file is not a plain .js file, but a "vue templating language" file. In order to run vue app in a browser, you firstly should compile it into regular JavaScript. To make it simpler for the compiler, you should follow "vue templating language" syntax rules. The example you provided shows some code that is not possible in regular HTML or JavaScript.

    According to the message you got compiled JavaScript tries to call hello_local method from the internal _ctx object, but as you haven’t followed the vue syntax rules, the function hello_local was not compiled to be in a _ctx object, resulting in the error.

    Login or Signup to reply.
  2. its simply not a part of the vue instance. if u want to use it in the template u have to add it to the methods. u can just assign it instead of calling it. methods: { hello }

    also with new vue 3 it is possible directly with setup

    https://vuejs.org/api/sfc-script-setup

    <script setup>
    import { capitalize } from './helpers'
    </script>
    
    <template>
      <div>{{ capitalize('hello') }}</div>
    </template>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search