6

I want to separate the vue.js template into a .vue file while leaving code in a .js file.

This is a vue "single file component":

<template>
..
</template>

<script>
..
</script>

What works:

Make the .vue file the real component, and define a MIXIN that points to the .js file. Seems very hacky!

What I would like:

A single webpack import to the .js file:

...
</template>

import ViewModel from 'vm.js'

Is this possible? Or a tag in the .vue file that vue-loader understands?

<template>
..
<script src='vm.js'/>
</template>

Thanks a ton! The goal is to set breakpoints in visual studio code + separation of concerns + readability. :)

Oh, and this needs to work with typescript!

2
  • 1
    As someone who is still learning vue, from what I understand is that vue needs the template/js in one file in order for it to be compiled into a component for web usage. However, if this is in fact possible I would like to know as well... Commented Apr 29, 2018 at 15:36
  • Can't you just wrap the import in script tags? Commented Apr 29, 2018 at 15:58

1 Answer 1

7
...
</template>

import ViewModel from 'vm.js'

The second option is possible with a small tweak made in it

<template>
...
</template>

<script src="vm.js"></script>
Sign up to request clarification or add additional context in comments.

4 Comments

Ok, thanks! I'll try it out and accept the answer if it works. :)
What about typescript... I'm working right now on moving our vue.js codebase to it. Do I just include a "vm.ts"? I'm not sure webpack and vue-loader is that smart...
Support for typescript is available. I haven't tried it yet for my projects though. You can check out vuejs.org/v2/guide/typescript.html
Looks like we might need to add: <script lang="ts">. Source: github.com/Microsoft/TypeScript-Vue-Starter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.