Home > Article > Web Front-end > How to use el in vue component
In the Vue component, the el attribute is used to specify the root element of the component, that is, the mount point. Through the el attribute, the component can be rendered to the specified element in the DOM.
When developing with Vue.js, there are usually two ways to specify the root element of a component.
One is to use the el attribute in the Vue instance to specify the root element. This method is suitable for instances created through new Vue().
The other is to use the el attribute inside the component to specify the root element. This method is suitable for registering components through Vue.component().
Let’s look at the first method first. When creating a Vue instance, you can specify the mount point through the el attribute, for example:
new Vue({ el: '#app', data: { message: 'Hello Vue.js!' } })
This will mount the Vue instance to the one with the id app on the elements. When the data changes, Vue will automatically update the relevant DOM elements in the page.
In components, since each component is independent, the root element also needs to be specified separately. This can be achieved by adding the el attribute to the component options, for example:
Vue.component('my-component', { template: '<p>{{ message }}</p>', data: function () { return { message: 'Hello Vue.js from component!' } }, el: '#component-container' })
This will render the component to the element with the id component-container. It should be noted that since components are reusable, the el attribute only works when the component is used alone. If the component is nested in other components, the el attribute of the parent component will be used.
In addition to using the el attribute for mounting, you can also manually mount components through the $mount() method. For example:
var vm = new Vue({ template: '<p>{{ message }}</p>', data: { message: 'Hello Vue.js!' } }) vm.$mount('#app')
This will mount the Vue instance to the element with the id app. It should be noted that if the el attribute is not specified, the component needs to be mounted manually.
In short, in Vue, the el attribute is used to specify the root element of a component. By rationally using the el attribute, flexible mounting and reuse of components can be achieved.
The above is the detailed content of How to use el in vue component. For more information, please follow other related articles on the PHP Chinese website!