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 id="mac" > <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',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 自定義元件內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!