chemist
chemist

Reputation: 373

How to insert external javascript into a Vue component

I am trying to insert a custom JavaScript (a sketcher) into a Vue component but no luck so far. When I try inserting javascript directly into a template like this:

<template>
    <div id="sketcher">
        var sketcher = new ChemDoodle.SketcherCanvas('sketcher', 400, 300);
    </div>
</template>

I get an error: "Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as , as they will not be parsed." My another attempt is to create a component in a different .js file and import it into a Vue component.

sketcher.js:

export default ({
  mounted(){    
   return new ChemDoodle.SketcherCanvas('sketcher', 400, 300)
  }
})

Home.vue

<template>
    <div id="sketcher">
       <app-sketcher></app-sketcher>
    </div>
</template>

<script>
import sketcher from './sketcher';    
export default {
    components: {
    "app-sketcher": sketcher
    }
}
</script>

but I get this error: "Failed to mount component: template or render function not defined". I would highly appreciate any suggestions on how to fix this or to propose other options of embedding javascript into a Vue component.

Upvotes: 0

Views: 1212

Answers (1)

thanksd
thanksd

Reputation: 55664

Your first error message is self-explanatory: you cannot put a <script> tag in the <template> of a single-file Vue component.

In your second example, you aren't defining a template for the app-sketcher component when you register it in your Home.vue file. Your sketcher.js file exports just the definition for a mounted hook and nothing else.


You can make a Sketcher.vue file:

<template>
  <div id="sketcher"></div>
</template>

<script>
export default {
  mounted() {    
    return new ChemDoodle.SketcherCanvas('sketcher', 400, 300)
  }
}
</script>

And then use import it and use it in your Home.vue file like so:

<template>
  <app-sketcher/>
</template>

<script>
import AppSketcher from './Sketcher';    
export default {
  components: { AppSketcher }
}
</script>

Upvotes: 1

Related Questions