Vue組件間傳遞數據

組件是Vue很強大的一個功能,因此掌握Vue組件之間的信息傳遞很重要。大體分爲三種常見的狀況。javascript

  • 父組件向子組件傳遞數據
  • 子組件向父組件傳遞數據
  • 兄弟組件傳遞數據

下面咱們就這三種狀況,分別演示其方法css

父組件經過rop向子組件傳遞數據

Prop 是你能夠在組件上註冊的一些自定義特性。當一個值傳遞給一個 prop 特性的時候,它就變成了那個組件實例的一個屬性。html

  • 一個組件能夠擁有任意數量的prop
  • 任何值均可以傳遞給任何prop
    demo
<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的設計模式——觀察者模式,dispatchEventaddEventListener。在Vue中,子組件用$emit()來觸發事件,父組件用$on() 來監聽子組件的事件。vue

  • 自定義事件
  • 在子組件中用$emit觸發事件,第一個參數是事件名,後邊的參數是要傳遞的數據
  • 在自定義事件中用一個參數來接受
    demo
<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>
複製代碼

使用bus進行兄弟組件傳遞數據

在兄弟組件進行數據傳遞時,一般的作法是使用一個空的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.$parentapp

子鏈(利用索引)

<my-component ref='xxx'>
複製代碼

this.$refs.xxxpost

相關文章
相關標籤/搜索