Vue Component Instance

In Vue.js, a component instance is one of the most fundamental building blocks of a Vue application. Each component instance is a Vue component that has its own template, data, methods, and lifecycle hooks, and can independently manage its own state and behavior. The following is a detailed introduction to Vue component instances:

Creating a Vue Component Instance

In Vue.js, a component instance is typically created using the createApp method and a component options object.

The component options object can contain the following properties:

  • data: Data object, used to store the component's reactive data.
  • props: Props array or object, used to receive data passed from the parent component.
  • computed: Computed properties object, dynamically calculated based on reactive dependencies.
  • methods: Methods object, containing functions and operations within the component.
  • watch: Watchers object, used to watch data changes and respond accordingly.
  • template: String, defining the template structure of the component.
  • render: Function, used to render the component's virtual DOM.
  • setup: Function, used to set up the component's initial state, data, computed properties, and watchers (in Vue 3).

The following is an example of a simple Vue component instance:

Example

import { createApp } from 'vue';

const app = createApp({
  data() {
    return {
      message: 'Hello, Vue!'
    };
  },
  methods: {
    greet() {
      alert(this.message);
    }
  },
  template: `
    <div>
      <p>{{ message }}</p>
      <button @click="greet">Greet</button>
    </div>
  `
});

app.mount('#app');

Explanation:

  • dataThe function returns an object containing amessageproperty, used to store the component's state.
  • methodsThe object contains agreetmethod; when the button is clicked, an alert box pops up displayingmessagethe content of.
  • templateThe string defines the component's template structure, using interpolation and event binding to achieve data display and interaction.

Lifecycle Hooks

Vue component instances have lifecycle hook functions that allow developers to execute custom logic at different stages of the component's lifecycle. Common lifecycle hooks includecreated、mounted、updatedanddestroyedetc.

Example

const app = createApp({
  data() {
    return {
      message: 'Hello, Vue!'
    };
  },
  created() {
    console.log('Component created');
  },
  mounted() {
    console.log('Component mounted');
  },
  updated() {
    console.log('Component updated');
  },
  destroyed() {
    console.log('Component destroyed');
  },
  template: `
    <div>
      <p>{{ message }}</p>
    </div>
  `
});

Component Communication

Vue component instances communicate with each other through props, events, provide/inject, $parent/$children, $attrs/$listeners, and other methods, depending on the relationship between components and their requirements. These mechanisms allow components to pass data between different levels and respond to user interactions.


Component Instance Properties

$data

The $data property contains all the data properties of the component instance. It is reactive, meaning that when data changes, the related views are automatically updated.

Example

const app = Vue.createApp({
  data() {
    return {
      message: 'Hello, Vue!'
    };
  }
});

const vm = app.mount('#app');
console.log(vm.$data); // { message: 'Hello, Vue!' }

$props

The $props property contains all the props passed from the parent component that the current component receives. It is read-only.

Example

<!-- ParentComponent.vue -->
<template>
  <child-component :message="parentMessage"></child-component>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      parentMessage: 'Message from parent'
    };
  }
};
</script>

Example

// ChildComponent.vue
export default {
  props: ['message'],
  mounted() {
    console.log(this.$props.message); // 'Message from parent'
  }
};

$refs

$refs contains all DOM elements or child component instances within the component that have the ref attribute. These elements or component instances can be accessed through $refs.

Example

<template>
  <div>
    <input type="text" ref="inputField">
  </div>
</template>

<script>
export default {
  mounted() {
console.log(this.$refs.inputField); // Access DOM element
this.$refs.inputField.focus(); // Call DOM element method
  }
}
</script>

The $el property represents the root DOM element of the current component instance. This property can only be accessed after the component is mounted.

Example

const app = Vue.createApp({
  template: '<div>Hello, Vue!</div>'
});

const vm = app.mount('#app');
console.log(vm.$el); // <div id="app">Hello, Vue!</div>

$attrs

$attrs contains all attributes passed from the parent component to the current component but not declared in the child component. These attributes can be used to pass additional non-prop attributes to child components.

Example

<!-- ParentComponent.vue -->
<template>
  <child-component custom-attr="value"></child-component>
</template>

<!-- ChildComponent.vue -->
<script>
export default {
  mounted() {
    console.log(this.$attrs); // { custom-attr: 'value' }
  }
};
</script>

$listeners

$listeners contains all listeners (event handlers) passed from the parent component to the current component, and can be directly bound to the component's root element or other elements.

Example

<!-- ChildComponent.vue -->
<template>
  <button v-on="$listeners">Click me</button>
</template>

<script>
export default {
  mounted() {
    console.log(this.$listeners); // { click: handleClick }
  },
  methods: {
    handleClick() {
      console.log('Button clicked');
    }
  }
};
</script>

Component Instance Methods

$mount()

The $mount() method manually mounts a Vue component to a DOM element. In Vue 3, mounting is usually done automatically via createApp().mount(), and manual mounting is needed only in a few cases.

Example

const app = Vue.createApp({
  template: '<div>Hello, Vue!</div>'
});

const vm = app.mount('#app');

$destroy()

The $destroy() method destroys the current component instance, unbinds all its event listeners, and releases the resources it occupies. It is useful in specific scenarios, such as dynamically creating and destroying components.

Example

vm.$destroy();

$emit()

The $emit() method is used to trigger custom events on the current component instance and pass data to the parent component. It is usually used together with the v-on directive.

Example

<button @click="$emit('custom-event', eventData)">Click me</button>

$nextTick()

The $nextTick() method executes the specified callback function after the next DOM update cycle ends. It is used to perform some operations after the DOM is updated.

Example

vm.$nextTick(() => {
  // Operations performed after the DOM update is complete
});

$watch()

The $watch() method is used to watch data changes on the component instance and execute the specified callback function when data changes.

Example

vm.$watch('message', (newValue, oldValue) => {
  console.log(`Message changed from ${oldValue} to ${newValue}`);
});

These properties and methods give Vue component instances rich functionality and flexibility, able to meet developers' various needs when building complex applications. From data management to event handling, and then to dynamic component operations, everything can be managed and controlled through component instances.

Other Extensions