Vue-Vue組件的註冊和使用

全局註冊:html

  要註冊一個全局組件,可使用 Vue.component(tagName, options)瀏覽器

  注意確保在初始化根實例以前註冊組件:函數

html代碼:spa

<div id="example">
  <my-component></my-component>
</div>

JS代碼:code

// 註冊
Vue.component('my-component', { template: '<div>A custom component!</div>' }) // 建立根實例
new Vue({ el: '#example' })
渲染爲:
<div id="example">
  <div>A custom component!</div>
</div>
 
局部註冊:
 
  沒必要把每一個組件都註冊到全局。能夠經過某個 Vue 實例/組件的實例選項 註冊僅在其做用域中可用的組件:components
var Child = { template: '<div>A custom component!</div>' } new Vue({ // ...
 components: { // <my-component> 將只在父組件模板中可用
    'my-component': Child } })
注意點:

  一:DOM 模板解析注意事項component

  當使用 DOM 做爲模板時 (例如,使用 el 選項來把 Vue 實例掛載到一個已有內容的元素上),你會受到 HTML 自己的一些限制,由於 Vue 只有在瀏覽器解析、規範化模板以後才能獲取其內容。尤爲要注意,像 <ul><ol><table><select> 這樣的元素裏容許包含的元素有限制,而另外一些像 <option> 這樣的元素只能出如今某些特定元素的內部。在自定義組件中使用這些受限制的元素時會致使一些問題,例如:htm

<table>
  <my-row>...</my-row>
</table>
  
    自定義組件  會被看成無效的內容,所以會致使錯誤的渲染結果。變通的方案是使用特殊的  特性:<my-row>is
 
<table>
  <tr is="my-row"></tr>
</table>

  2、data 必須是函數對象

var Child={ template:'<p>{{msg}}</p>', data:{ msg:'lizhao' } }

  當data時對象格式時,Vue 會中止運行,並在控制檯發出警告,告訴你在組件實例中 data 必須是一個函數。由於組件實例共享同一個 data 對象,修改一個變量會影響全部組件!咱們能夠經過爲每一個組件返回全新的數據對象來修復這個問題:blog

var Child={ template:'<p>{{msg}}</p>', data:function(){ return{ msg:'lizhao' } } }
相關文章
相關標籤/搜索