組件(Component)是 Vue.js 最強大的功能之一。組件能夠擴展 HTML 元素,封裝可重用的代碼。javascript
註冊一個全局組件語法格式以下:java
Vue.component(tagName, options)
tagName 爲組件名,options 爲配置選項。註冊後,咱們可使用如下方式來調用組件:app
<tagName></tagName>
1.全局組件:this
全部實例都能用全局組件spa
<div id="app"> <aaa></aaa> <aaa></aaa> </div> <script> Vue.component('aaa',{ template:'<h1>自定義組件!</h1>' }) new Vue({ el:'#app' }) </script>
2.局部組件:3d
在實例選項中註冊局部組件,這樣組件只能在這個實例中使用code
<div id="app"> <cc></cc> </div> <script type="text/javascript"> var Child = { template: '<h1>自定義組件!</h1>' }; new Vue({ el:'#app', components:{ 'cc':Child } }) </script>
3.參數:props component
傳遞參數給組件blog
<body> <div id="app"> <aaa mess="abcd"></aaa> <aaa></aaa> </div> <script> Vue.component('aaa',{ props:['mess'], template:'<h1>---{{mess}}----</h1>' }) new Vue({ el:'#app' }) </script> </body>
4.動態參數ip
<div id="app"> <div> <input v-model="parentMsg"> <br> <child v-bind:message="parentMsg"></child> </div> </div> <script> // 註冊 Vue.component('child', { // 聲明 props props: ['message'], // 一樣也能夠在 vm 實例中像 「this.message」 這樣使用 template: '<span>{{ message }}</span>' }) // 建立根實例 new Vue({ el: '#app', data: { parentMsg: '父組件內容' } }) </script>