組件是Vue很強大的一個功能,因此掌握Vue組件之間的信息傳遞很重要。大體分爲三種常見的狀況。javascript
下面咱們就這三種狀況,分別演示其方法css
Prop 是你能夠在組件上註冊的一些自定義特性。當一個值傳遞給一個 prop 特性的時候,它就變成了那個組件實例的一個屬性。html
<div id="app">
<my-component title="我是第一個組件"></my-component>
<my-component title="我是第二個組件"></my-component>
<my-component title="我是第三個組件"></my-component>
</div>
<script src="https://cdn.bootcss.com/vue/2.5.17/vue.js"></script>
<script> Vue.component('my-component', { props: ['title'], template: '<h2>{{title}}</h2>' }) new Vue({ el: '#app', data: {}, }) </script>
複製代碼
相似於JavaScript的設計模式——觀察者模式,dispatchEvent
和addEventListener
。在Vue中,子組件用$emit()
來觸發事件,父組件用$on()
來監聽子組件的事件。vue
$emit
觸發事件,第一個參數是事件名,後邊的參數是要傳遞的數據<div id="app">
<div :style="{ fontSize: postFontSize + 'em' }">
<blog-post v-for="post in posts" v-bind:key="post.id" v-bind:post="post" @change="enlargeText" ></blog-post>
</div>
</div>
<script> Vue.component('blog-post', { props: ['post'], template: ` <div class="blog-post"> <h3>{{ post.title }}</h3> <button @click="$emit('change')"> 增大字號 </button> <div v-html="post.content"></div> </div> ` }) new Vue({ el: '#app', data: { posts: [ {id: 1, title: '我是標題一'}, {id: 2, title: '我是標題二'}, {id: 3, title: '我是標題三'} ], postFontSize: 1 }, methods: { enlargeText: function () { this.postFontSize += 0.1 } } }) </script>
複製代碼
在兄弟組件進行數據傳遞時,一般的作法是使用一個空的Vue實例做爲中央事件總線:java
var bus = new Vue()
複製代碼
//觸發組件A中的事件
bus.$emit('id-selected',1)
複製代碼
//在組件B建立的鉤子中監聽事件
bus.$on('id-selected',function(id){
//...
})
複製代碼
demo設計模式
<div id="app">
<first-component></first-component>
<second-component></second-component>
</div>
<script> Vue.component('first-component', { template: `<div><button @click="handle">點我向b組件傳遞數據</button></div>`, data: function () { return { aaa: '我是來自A組件的內容' } }, methods: { handle: function () { this.$root.bus.$emit('haha', this.aaa) } } }) Vue.component('second-component', { template: `<div>我是一個組件</div>`, created: function () { this.$root.bus.$on('haha', function (value) { alert(value) }) } }) new Vue({ el: '#app', data: { bus: new Vue() } }) </script>
複製代碼
this.$parent
app
<my-component ref='xxx'>
複製代碼
this.$refs.xxx
post