Vue 創(chuàng)建組件的兩種方法小結(必看)
創(chuàng)建組件的兩種方法小結
1.全局注冊
2.局部注冊
var child=Vue.extend({})
var parent=Vue.extend({})
Vue.extend() 全局方法 生成構造器,創(chuàng)建子類
使用基礎 Vue 構造器,創(chuàng)建一個“子類”。
這樣寫非常繁瑣。于是vue進行了簡化
使用Vue.component()直接創(chuàng)建和注冊組件:
Vue.component(id,options) 全局方法 用來注冊全局組件
id 是string類型,即是注冊組件的名稱
options 是個對象
// 全局注冊,my-component1是標簽名稱
Vue.component('my-component1',{
template: '<div>This is the first component!</div>'
})
var vm1 = new Vue({
el: '#app1'
})
Vue.component()的第1個參數(shù)是標簽名稱,第2個參數(shù)是一個選項對象,使用選項對象的template屬性定義組件模板。
使用這種方式,Vue在背后會自動地調用Vue.extend()。
在選項對象的components屬性中實現(xiàn)局部注冊:
var vm2 = new Vue({
el: '#app2',
components: {
// 局部注冊,my-component2是標簽名稱
'my-component2': {
template: '<div>This is the second component!</div>'
},
// 局部注冊,my-component3是標簽名稱
'my-component3': {
template: '<div>This is the third component!</div>'
}
}
})
==局部注冊都放在選項對象中創(chuàng)建==
注意:這里是components,里面可以定義多個組件。
簡化后是這樣的寫法
<body>
<div id='box'>
<parent>
</parent>
</div>
<script src='js/vue.js'></script>
<script>
Vue.component('parent',{
template:`<div><h1>我是父組件</h1><child></child></div>`,
components:{
'child':{
template:`<h1>我是子組件</h1>`
}
}
})
new Vue({
el:'#box'
})
</script>
</body>
注冊一個parent的父組件。然后在父組件的選項對象中注冊一個child的子組件。將子組件child的標簽寫到父組件parent的template里面。
頁面上的樣式結構就是
<div> <h1>我是父組件</h1> <h1>我是子組件</h1> </div>
注意:用局部注冊的子組件不能單獨直接使用!
標簽掛在div里,會報錯
<div id='box'> <child></child> </div>
結果會報錯。
以上這篇Vue 創(chuàng)建組件的兩種方法小結(必看)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Vue實現(xiàn)下拉滾動加載數(shù)據(jù)的示例
這篇文章主要介紹了Vue實現(xiàn)下拉滾動加載數(shù)據(jù)的示例,幫助大家更好的理解和學習使用vue框架,感興趣的朋友可以了解下2021-04-04
詳解Vue SSR( Vue2 + Koa2 + Webpack4)配置指南
這篇文章主要介紹了詳解Vue SSR( Vue2 + Koa2 + Webpack4)配置指南,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11
深入解析Vue中的this.$forceUpdate()的使用
this.$forceUpdate()?是一個重要的實例方法,本文主要介紹了深入解析Vue中的this.$forceUpdate()的使用,具有一定的參考價值,感興趣的可以了解一下2024-07-07

