3
votes

I have very simple single file component, defined in checkbox-wrapper.vue:

<template id="checkbox-wrapper">
  <div class="checkbox-wrapper" @click="check">
    <div :class="{ checkbox: true, checked: checked }"></div>
    <div class="title">{{ title }}</div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      checked: false,
      title: "Check me"
    };
  },
  methods: {
    check() {
      this.checked = !this.checked;
    }
  }
};
</script>

I've had successfully build this component with webpack to checkbox-wrapper.js.

Here is app1.js:

Vue.component('checkbox-wrapper',{
  template: "#checkbox-wrapper"
});



var app1 = new Vue({
  el: "#app1",
  data: {},
  methods: {}
});

And index.html, where I've tried to show this component:

<!DOCTYPE html>
<html>
    <head>
        <title>Empty project</title>
        <meta charset="utf-8">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
        <script src="checkbox-wrapper.js"></script>
    </head>
    <body>
        <div id="app1">
            <checkbox-wrapper></checkbox-wrapper>
        </div>

        <script src="app1.js"></script>
    </body>
</html>

I am receiving errors:

[Vue warn]: Cannot find element: #checkbox-wrapper

[Vue warn]: Template element not found or is empty: #checkbox-wrapper

[Vue warn]: Failed to mount component: template or render function not defined.

I don't understand what am I doing wrong - component is included and registered before initialization of vue. I was following advice from here, but it's not working for me.

2
If you have a single-file component, you should import it for use in local registration. See the "ES2015 modules" example here ~ vuejs.org/v2/guide/… - Phil
I am really struggling with this - can you please provide working example. - FrenkyB

2 Answers

1
votes

Your approach seems strange to me.

I was following advice from here

But your setup is via webpack, it's different from him, he was using the cdn approach, he mounted vue component directly to an HTML element whose id in an actual HTML page (not just id of a vue template). This is the approach usually for small testing projects btw, those don't care about performance.

About setting up a project, If not really needed, just use the vue-cli instead of config webpack yourself. The instructuion is pretty awesome so I believe you'll easily make it work.

0
votes

What solved my problem:

import Vue from "vue";
import firstComp from "./first-component";

new Vue({
  el: "#app",
  components: {
    "first-component": firstComp
  }
});

That file must be transpiled, than transpiled .js included inside html and it's ok using this syntax:

<div id="app">
      <first-component></first-component>
</div>