怎么在vue中嵌套父子組件?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
先創建一個構造器
var myComponent = Vue.extend({
template: '...'
})用Vue.component注冊,將構造器用作組件(例為全局組件)
Vue.component('my-component' , myComponent)注冊局部組件:
var Child = Vue.extend({ /* ... */ })
var Parent = Vue.extend({
template: '...',
components: {
// <my-component> 只能用在父組件模板內
'my-component': Child
}
})注冊語法糖,簡化過程
// 在一個步驟中擴展與注冊
Vue.component('my-component', {
template: '<div>A custom component!</div>'
})
// 局部注冊也可以這么做
var Parent = Vue.extend({
components: {
'my-component': {
template: '<div>A custom component!</div>'
}
}
})父子組件嵌套的例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>index</title>
</head>
<body>
<div id="app">
<parent></parent>
</div>
<script src="vue.js"></script>
<script>
var childComponent = Vue.extend({
template: '<p>this is child template</p>'
});
Vue.component("parent",{
template: '<p>this is parent template</p><child></child><child></child>',
components: {
'child': childComponent,
}
});
var app = new Vue({
el: '#app'
});
</script>
</body>
</html>其與以下寫法等價:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>index</title>
</head>
<body>
<template id="child">
<p>this is child template</p>
</template>
<template id="parent">
<p>this is parent template</p>
<child></child>
<child></child>
</template>
<div id="app">
<parent></parent>
</div>
<script src="vue.js"></script>
<script>
var childComponent = Vue.extend({
template: '#child'
});
Vue.component("parent",{
template: '#parent',
components: {
'child': childComponent,
}
});
var app = new Vue({
el: '#app'
});
</script>
</body>
</html>頁面顯示:

看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。