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在背后會自動地調(diào)用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)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Antd-vue Table組件添加Click事件,實現(xiàn)點擊某行數(shù)據(jù)教程
這篇文章主要介紹了Antd-vue Table組件添加Click事件,實現(xiàn)點擊某行數(shù)據(jù)教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11Vue3中SetUp函數(shù)的參數(shù)props、context詳解
我們知道setup函數(shù)是組合API的核心入口函數(shù),下面這篇文章主要給大家介紹了關于Vue3中SetUp函數(shù)的參數(shù)props、context的相關資料,需要的朋友可以參考下2021-07-07使用Vue.set()方法實現(xiàn)響應式修改數(shù)組數(shù)據(jù)步驟
今天小編就為大家分享一篇使用Vue.set()方法實現(xiàn)響應式修改數(shù)組數(shù)據(jù)步驟,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11vue excel上傳預覽和table內(nèi)容下載到excel文件中
這篇文章主要介紹了vue excel上傳預覽和table內(nèi)容下載到excel文件中,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-12-12