Vue Instance Options
Options in Vue are the different options available on a Vue instance when using the Options API.
Some common options of Vue instances:
-
el- Specifies the DOM element to which the Vue instance is mounted. If not provided, the Vue instance will not be mounted automatically.
-
data- Defines the data object of the Vue instance. The template, computed properties, methods, watchers, etc. of the Vue instance can access this data.
-
computed- Contains computed properties whose values are cached based on their dependencies. Computed properties are only re-evaluated when their dependencies change.
-
methods- Defines methods of the Vue instance that can be called in the template through event listeners.
-
watch- Contains one or more watchers to observe and respond to data changes in the Vue instance.
-
props- Defines external data that the component can receive.
-
components- Allows registering custom components in the Vue instance.
-
directives- Allows registering global custom directives.
-
filters- Defines filters that can be used in the template for text formatting.
-
model- Specifies custom v-model properties and events used by the component.
-
provide/inject- Provides dependency injection capability, allowing data to be passed across components.
-
lifecycle hooks- Includes
onMounted,onUpdated,onUnmountedlifecycle hooks, etc., used to execute code at different stages of the Vue instance. -
template- Defines the HTML template of the Vue instance.
-
render function- Allows using JavaScript functions to render components, providing more advanced customization capabilities.
-
errorCaptured- Used to globally capture errors in the Vue instance.
-
emits- Defines events that the component can emit.
-
setup- The entry function in Vue 3's Composition API, used to organize component logic.
el
Mount point, used to specify the DOM element to which the Vue instance is mounted:
Example
// options
});
app.mount('#app');
data
-
Type: Function or Object
-
Purpose:
datais the place in the Vue instance used to store component data. You candatadefine various data properties in it and use them on the page through template syntax.dataThe data in it updates reactively, meaning that when the data changes, the related page content automatically updates.
Example
data() {
return {
message: 'Hello Vue!'
};
}
});
computed
-
Type: Object
-
Purpose:
computedThe property allows you to declare computed properties based on reactive dependencies. Computed properties are only re-evaluated when their related dependencies change, and they cache the computed results to avoid unnecessary repeated calculations.
Example
data() {
return {
firstName: 'John',
lastName: 'Doe'
};
},
computed: {
fullName() {
return `${this.firstName} ${this.lastName}`;
}
}
});
methods
-
Type: Object
-
Purpose:
methodsThe property is used to store methods in the Vue instance. These methods can be called in the template and also used in other methods of the instance. Unlike computed properties, methods are re-executed every time they are called, making them suitable for responding to events or performing asynchronous operations.
Example
data() {
return {
count: 0
};
},
methods: {
increment() {
this.count++;
}
}
});
watch
-
Type: Object or Function
-
Purpose:
watchThe property is used to observe and respond to data changes in the Vue instance. When the watched data changes, the specified callback function is executed. It is suitable for handling asynchronous or complex data-change logic.
Example
data() {
return {
message: 'Hello Vue!'
};
},
watch: {
message(newValue, oldValue) {
console.log(`Message changed from ${oldValue} to ${newValue}`);
}
}
});
props
-
Type: Array or Object
-
Purpose:
propsThe property is used to receive data passed from the parent component to the child component. In the child component,propsthe data passed by the parent component is received and can be used inside the component.
In the following example, MyComponent receives a title prop and uses it in the template:
Example
props: ['title'],
template: '<h1>{{ title }}</h1>'
};
const app = Vue.createApp({
components: {
'my-component': MyComponent
},
template: '<my-component title="Hello Vue 3!"></my-component>'
});
app.mount('#app');
template
-
Type: String
-
Purpose:
templateThe property defines the template structure of the Vue component. Vue's template syntax can be used in the template, including interpolation, directives, computed properties, etc. The template is eventually compiled into a render function to generate the component's virtual DOM.
Example
data() {
return {
message: 'Hello Vue!'
};
},
template: '<div>{{ message }}</div>'
});
components
The `components` option is used to register local components.
Example
template: '<div>A child component</div>'
};
const app = Vue.createApp({
components: {
'child-component': ChildComponent
},
template: '<child-component></child-component>'
}).mount('#app');
provide / inject
The parent component provides data, and the child component injects and uses it.
Example
inject: ['message'],
template: '<div>{{ message }}</div>'
};
const app = Vue.createApp({
provide() {
return {
message: 'Provided Message'
};
},
components: {
'child-component': ChildComponent
},
template: '<child-component></child-component>'
}).mount('#app');
Lifecycle Hooks
beforeCreate
Called before the instance is initialized.
Example
beforeCreate() {
console.log('beforeCreate');
}
}).mount('#app');
created
Called after the instance has been created.
Example
created() {
console.log('created');
}
}).mount('#app');
beforeMount
Called before mounting.
Example
beforeMount() {
console.log('beforeMount');
}
}).mount('#app');
mounted
Called after the instance has been mounted.
Example
mounted() {
console.log('mounted');
}
}).mount('#app');
beforeUpdate
Called before data is updated.
Example
data() {
return {
message: 'Hello'
};
},
beforeUpdate() {
console.log('beforeUpdate');
}
}).mount('#app');
updated
Called after data is updated.
Example
data() {
return {
message: 'Hello'
};
},
updated() {
console.log('updated');
}
}).mount('#app');
beforeUnmount
Called before the instance is unmounted.
Example
beforeUnmount() {
console.log('beforeUnmount');
}
}).mount('#app');
unmounted
Called after the instance is unmounted.
Example
unmounted() {
console.log('unmounted');
}
}).mount('#app');
Other Options
directives
Register local directives.
Example
directives: {
focus: {
mounted(el) {
el.focus();
}
}
},
template: '<input v-focus>'
}).mount('#app');
mixins
Mixin objects.
Example
created() {
console.log('Mixin created');
}
};
const app = Vue.createApp({
mixins: [myMixin],
created() {
console.log('Component created');
}
}).mount('#app');
extends
Extend another component.
Example
created() {
console.log('BaseComponent created');
}
};
const app = Vue.createApp({
extends: BaseComponent,
created() {
console.log('Extended component created');
}
}).mount('#app');
inheritAttrs
Whether to inherit attributes from the parent component.
Example
inheritAttrs: false,
props: ['title'],
template: '<div><h1>{{ title }}</h1></div>'
};
const app = Vue.createApp({
components: {
'my-component': MyComponent
},
template: '<my-component title="Hello" id="app"></my-component>'
}).mount('#app');
setup
Used for the Composition API.
Example
setup() {
const message = Vue.ref('Hello Vue 3!');
return { message };
},
template: '<h1>{{ message }}</h1>'
}).mount('#app');
expose
In Vue 3's Composition API, when using the setup function to define component logic, you can use the expose method to explicitly specify the properties and methods to be exposed to the outside.
The following is a simple example showing how to use expose to expose properties and methods in a Vue 3 component:
Parent Component (ParentComponent.vue)
<div>
<child-component ref="child"></child-component>
<button @click="callChildMethod">Call Child Method</button>
</div>
</template>
<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
setup() {
const child = ref(null);
const callChildMethod = () => {
if (child.value) {
child.value.exposedMethod();
}
};
return {
child,
callChildMethod
};
}
};
</script>
Child Component (ChildComponent.vue)
<div>
<p>{{ exposedData }}</p>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup(_, { expose }) {
const exposedData = ref('Hello from Child Component');
const exposedMethod = () => {
console.log('Child component method called');
};
expose({
exposedData,
exposedMethod
});
return {
exposedData
};
}
};
</script>
Explanation:
Parent component:
- In the parent component, use
refto create a reference to the child component.child。 - In
callChildMethodIn the method, throughchild.valueaccess the child component's instance and call the methods exposed by the child component.exposedMethod。
- In the parent component, use
Child component:
- In the child component's
setupfunction, throughrefcreate a reactive dataexposedData。 - define a method
exposedMethod, used to show how to expose methods. - Use
exposethe method to explicitly exposeexposedDataandexposedMethodto the parent component. - Return
exposedData, so that it can be used in the template.
- In the child component's