Search code snippets, questions, articles...

Define a new component in Vue.js

In this article, we will focus on how to define a new component in Vue.js. We will look at the different options for doing so. If you are not using the build step and want to create all HTML in your js file then you can use the below code.
Vue.component('component_name', {
    props: ['prop_name'],
    template: '<div class="root"></div>',
    data() {
        return {}
    },
    methods: {
    },
    created() {
    }
});

If you are using build steps and want to create the components in your .vue file then you can use the below code example to define a new component.

counter.vue file

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

<template>
  <button @click="count++">Counter: {{ count }}</button>
</template>

We have created a file counter.vue for our component and placed the above code. We have defined a variable count that starts from 0 and on button click, we are increasing it's value by 1.

Was this helpful?
0 Comments