VueJs Component

Vue Components

are one of the important features of VueJS that creates custom elements, which can be reused in HTML and they help you extend basic HTML elements to encapsulate reusable code.

<div id="component_test">
    <testcomponent></testcomponent>
</div>
<div id="component_test1">
  <testcomponent></testcomponent>
</div>
<script>
Vue.component('testcomponent', {
  template : '<div><h3>This is coming from component</h3></div>'
});
var vm = new Vue({
  el : '#component_test'
});
var vm1 = new Vue({
  el : '#component_test1'
});
</script>

Output

Components and Passing Data

If you're familiar with React or Angular, the idea of components and passing state won't be new to you. In case you're not, let's go through some of the main concepts.

new Vue({
  el: 'app_component', 
  template: '<h1>Hello VueJs</h1>'
})

This works, but isn't terribly useful as it can only be used once and we're not yet passing the information to different components. One way to pass data from a parent to a child is called props.

:name in the HTML is a shortcut for Vue binding. Binding can be used for all kinds of things but in this instance, it keeps us from having to place the state in a mustache template, like this {{ name }}.

Below, Vue.component is the component, and new Vue is called the instance. You can have more than one instance in an application. Typically, we'll have one instance and several components, as the instance is the main app.

<div id="my_test_component">
    <mycomponent :name="createby"></mycomponent>
</div>
<div id="my_test_component1">
  <mycomponent :name="createby"></mycomponent>
</div>
<script>
Vue.component('mycomponent', {
  template : '<div><h3>Component is created by {{ name }}</h3></div>',
  props: ["name"]
});
var vm = new Vue({
  el : '#my_test_component',
  data: {
    createby: "Evan You"
  }
});
var vm1 = new Vue({
  el : '#my_test_component1',
  data: {
    createby: "Saarthak Singh"
 }
});
</script>

Output