3

I am new in vue js, I am learning components. I have created a basic program containing component. Following are my files

project/src/main.js

import Vue from 'vue'
window.Vue = Vue;

import ButtonCounter from './components/ButtonCounter.vue'

new Vue({
    el: '#components-demo',
    render: h => h(ButtonCounter)
})

project/src/components/ButtonCounter.vue

<template>
<div id="components-demo">
<button-counter></button-counter>
</div>
</template>

<script>
// Define a new component called button-counter
Vue.component('button-counter', {
  data: function () {
    return {
      count: 0
    }
  },
  template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})
</script>

When I execute this, I get following error, even though I have declared Vue globally in main.js

enter image description here

1
  • JS modules are independent chunks of code. So if you need to use Vue in the module, you'd have to import it inside the module. Commented Sep 27, 2018 at 6:35

2 Answers 2

2

So it looks like you took the component definition and just moved to another file. If you move to another file you don't need to use Vue.component. You just export an object containing the data, methods, etc. that you want attached to the component. And inside the Vue instance you attach the imported component via the components property. I.e.

Main index.html

<div id="components-demo">
  <button-counter></button-counter>
</div>

Component.vue

<template>
  <button v-on:click="count++">You clicked me {{ count }} times.</button>
</template>

<script>
export default {
  data: function () {
    return {
      count: 0
    }
  }
})
</script>

Then inside your main file

import Vue from 'vue'
// window.Vue = Vue; -- don't need this anymore

import ButtonCounter from './components/ButtonCounter.vue'

new Vue({
    el: '#components-demo',
    render: h => h(ButtonCounter),
    components: {ButtonCounter}
})
Sign up to request clarification or add additional context in comments.

Comments

0

The error is in this line

window.Vue = Vue;

Just import and create a new instance of Vue

import Vue from 'vue'
import ButtonCounter from './components/ButtonCounter.vue'

new Vue({
    el: '#components-demo',
    render: h => h(ButtonCounter)
})

Comments

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.