組件的出現,就是為了拆分Vue實例的代碼量的,能夠讓我們以不同的組件,來划分不同的功能模塊,將來我們需要什么樣的功能,就可以去調用對應的組件即可。
組件化和模塊化的不同:
模塊化:是從代碼邏輯的角度進行划分的;方便代碼分層開發,保證每個功能模塊的職能單一
組件化:是從UI界面的角度進行划分的;前端的組件化,方便UI組件的重用
方式一、
<div id='app'> <first-login></first-login> </div> <script> // 方式一
//聲明組件內容 var first = Vue.extend({ template: '<h1>第一種方式</h1>' }) // 全局注冊 參數一 組件名稱(組件名稱不支持駝峰命名) 參數二 組件內容 Vue.component('first-login',first) const vm = new Vue({ el: '#app', data: { }, methods: { }, }) </script>
方式二、
<div id='app'> <second-login></second-login> </div> <script> // 方式二 Vue.component('second-login',{ template:'<h1>第二種方式</h1>' }) const vm = new Vue({ el: '#app', data: { }, methods: { }, }) </script>
方式三、
<div id='app'> <!-- 方式三 --> <third-login></third-login> </div> <script type='template' id="third"> <h1>第三種方式</h1> </script> <script> // 方式三 Vue.component('third-login',{ template:'#third' }) const vm = new Vue({ el: '#app', data: { }, methods: { }, }) </script>
方式四、
<div id='app'> <!-- 方式四 --> <forth-login></forth-login> </div> <!-- 方法四 --> <template id="forth"> <!-- 只能有一個根元素 --> <h1>第四種方式</h1> </template> <script> // 方式四 Vue.component('forth-login', { template: '#forth' }) const vm = new Vue({ el: '#app', data: { }, methods: { }, }) </script>