組件是Vue.js最強大的功能之一。組件能夠擴展HTML元素,封裝可重用的代碼。在較高層面上,組件是自定義的元素,Vue.js的編譯器爲它添加特殊功能。在有些狀況下,組件也能夠是原生HTML元素的形式,以is特性擴展。css
一、註冊組件html
註冊組件就是利用Vue.component()
方法,先傳入一個自定義組件的名字,而後傳入這個組件的配置。vue
掛載到DOM元素中,使用Vue.component('mycomponent',{ template: `<div>這是一個自定義組件</div>`, data () { return { message: 'hello world' } } });
直接使用建立的組件,全部的Vue實例均可以使用。還能夠在某個Vue實例中註冊只有本身能使用的組件。
<div id="app"> <mycomponent></mycomponent> <my-component></my-component> </div> <script> var app = new Vue({ el: '#app', data: { }, components: { 'my-component': { template: `<div>這是一個局部的自定義組件,只能在當前Vue實例中使用</div>`, } } }) </script>
Vue.component()
注意:組件的模板只能有一個根元素。
屬性Props (父組件是使用 props 傳遞數據給子組件)var app = new Vue({ el: '#app', data: { }, components: { 'my-component': { template: `<div>這是一個局部的自定義組件,只能在當前Vue實例中使用</div>`, } } })
Vue.component('mycomponent',{ template: '<div>這是一個自定義組件,父組件傳給個人內容是:{{myMessage}}</div>', props: ['myMessage'], // 自定義特性 data () { return { message: 'hello world' } } })
html:
<my-component :my-message="message"><//my-component>
new Vue({
data:{
message:'Hello World'
}
})
自定義事件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 測試</title>
<script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment="incrementTotal"></button-counter>
<button-counter v-on:increment="incrementTotal"></button-counter>
</div>
</div>app
<script>
Vue.component('button-counter', {
template: '<button v-on:click="incrementHandler">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
incrementHandler: function () {
this.counter += 1
this.$emit('increment',this.counter) // 觸發父組件的方法, 事件名稱爲全小寫
}
},
})測試
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function (value) {
this.total = value
}
}
})
</script>
</body>
</html>this