Home > Article > Web Front-end > Does vue only have one vue root instance?
Vue.js is a very popular JavaScript framework in the field of front-end development. Its purpose is to build user interfaces through components so that developers can build web applications faster and more reliably.
A Vue application is composed of Vue instances. Analogy to a web application is composed of various components. The Vue instance is this component, including templates, data and methods. Simply put, the role of each Vue instance is to control the DOM of a specific area and handle some events of these DOM.
Normally, there is only one Vue root instance in a Vue application. This root instance can be created through the new Vue
function:
new Vue({ el: '#app', // 绑定的DOM元素 data: { // 数据 msg: 'Hello Vue!' }, methods: { // 方法 handleClick: function() { alert('Button Clicked!') } } })
In the above code, we bind a Vue instance to the #app
in the DOM on the elements. At the same time, a msg
data and a handleClick
method are specified, which can be used in HTML.
However, in some scenarios, we need to use multiple Vue instances in the same page. At this time we need to use the Vue.extend
method to create multiple instance components.
var childComponent = Vue.extend({ template: '<div>{{msg}}</div>', data: function() { return { msg: 'Hello Child Component!' } } }) new Vue({ el: '#app', components: { childComponent } })
In the above code, we use the Vue.extend
method to create a child component named childComponent
, and then use in the parent component components
attribute to introduce it. Just use the <child-component></child-component>
tag in your HTML.
In general, the most basic and important thing in a Vue application is the Vue instance. In most cases, a Vue application will only have one Vue root instance, but in some scenarios, multiple instances can coexist.
The above is the detailed content of Does vue only have one vue root instance?. For more information, please follow other related articles on the PHP Chinese website!