Vue自定義組件的四種方式示例詳解
四種組件定義方式都存在以下共性(血淚史)
規則:
1.組件只能有一個根標簽
2.記住兩個詞全局和局部
3.組件名稱命名中‘-小寫字母’相當于大寫英文字母(hello-com 相當于 helloCom)
而對于在HTML中自定義組件的時候有4種寫法,不過也只是殊途同歸,都是用template屬性對應的只有一個根標簽的HTML代碼。
1.全局組件
定義方式示例:
Vue.component('hello-component',{ props:['message'], template :'<div ><h1>組件定義之全局組件</h1><h4>{{message}}</h4></div>'});
使用
<hello-component message=' global component'></hello-component>
屬性介紹:
Vue.componen()是vue.js內部封裝方法'hello-component' 是使用時候的組件名稱props組件內的屬性。供給組件內部傳值template組件內部DOM元素組成
品鑒
全局組件定義方式,是直接給全局對象Vue注冊了一個組件。在本頁內已掛載Vue 實例的DOM目標元素 都可以使用(區別于局部組件只能是掛載哪一個DOM,哪個才能使用)。
2.局部組件
定義方式示例:
var limitComponent = { props:['message'], template :'<div><h1>{{message}}</h1><input type=’text’ v-model=’message’></input></div>'}new Vue ({ el : '#app', components :{ 'child-component': limitComponent }});
使用
<child-component message = '動態局部組件'></child-component>
屬性介紹:
el是 Vue 實例的掛載目標'components' 是注冊僅在其作用域中可用的組件'child-component'組件的名稱(書寫規則請上翻再看規則)limitComponent通過對象方式傳遞組件
品鑒
你不必把每個組件都注冊到全局。你可以通過某個 Vue 實例/組件的實例選項 components 注冊僅在其作用域中可用的組件。 js中用反斜線“”’實現字符串換行3.Script方式注冊組件
定義方式示例:
<script type='text/template' id='script-component'> <div > <h2>自定義組件之script方式定義</h2> <h4>{{message}}</h4> </div></script><script> Vue.component('mymac',{ props:['message'], template:'#script-component' }) var newVue = new Vue({ el:'#mac', data:{ mydata:'春暖花開' } });</script>
使用
<div > <input type='text' v-model='mydata' /> <mymac v-bind:message='mydata'></mymac></div>
屬性介紹:
<script type='text/template' id='script-component'>為定義組件的一種寫法,type還可以取的值還可以有:
text/javascript: 說明這一段腳本語言是javascript。告訴瀏覽器這一段要按照javascript來解釋執行。在ES5之前的type默認值 text/ecmascript:JavaScript和ECMAScript是相同的,只是在名稱上是不同的。但是對于ecmascript-6而言就可以理解是JS的新語法特性。即HTML5中的默認值 application/ecmascript: ie6、7、8都是沒法識別里面的js語句的 application/javascript: 這個屬性在IE8以下的瀏覽器中無法被識別。 text/vbscript: 表示該腳本語言是vb腳本品鑒
Script定義組件方式筆者覺得就是組件定義方式的另一種寫法。優點在于不用寫字符串式HTML代碼。將<script id='XX'>的XX賦值給局部組件或者全局組件都可。
4.<template>創建組件
定義方式示例:
<template id='cc'> <div > <h1>{{message}}</h1> </div> </template><script> Vue.component(’templatec’,{ props:['message'], template:'#cc' }) new Vue({ el:'#MyTemp' })</script>
使用
<div id='MyTemp'> <templatec message ='template組件之Template標簽'></templatec></div>
屬性介紹:
<template> 為HTML5發布后用來聲明是“模板元素”的標簽。即HTML5之前使用<script type ='text/template'>方式聲明,而HTML5之后可用<template> 標簽
品鑒
<template>定義組件的方式實際是HTML語法升級后的<script type ='text/template'>的另一種寫法。同script定義組件一樣,同樣可以配合定義全局/局部組件。
總結
通篇全文,介紹的四種方式。實際上只有兩種方式。要不就是全局定義方式,要不就是局部定義方式。另外兩種是為了增加代碼開發效率將字符串寫法換成標簽式書寫方式。
到此這篇關于Vuejs自定義組件的四種方式的文章就介紹到這了,更多相關vue 自定義組件內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: