Vue2.0組件間數據傳遞

Vue1.0組件間傳遞html

  使用$on()監聽事件;
  使用$emit()在它上面觸發事件;
  使用$dispatch()派發事件,事件沿着父鏈冒泡;
  使用$broadcast()廣播事件,事件向下傳導給全部的後代vue

Vue2.0後$dispatch(),$broadcast()被棄用,見https://cn.vuejs.org/v2/guide/migration.html#dispatch-和-broadcast-替換ide

 

1,父組件向子組件傳遞場景:Father上一個輸入框,根據輸入傳遞到Child組件上。ui

父組件:this

<template>
  <div>
    <input type="text" v-model="msg">
    <br>
    //將子控件屬性inputValue與父組件msg屬性綁定
    <child :inputValue="msg"></child>
  </div>
</template>
<style>

</style>
<script>
  export default{
    data(){
      return {
        msg: '請輸入'
      }
    },
    components: {
      child: require('./Child.vue')
    }
  }
</script

子組件:spa

<template>
  <div>
    <p>{{inputValue}}</p>
  </div>
</template>
<style>

</style>
<script>
    export default{
        props: {
          inputValue: String
        }
    }
</script>

2,子組件向父組件傳值場景:子組件上輸入框,輸入值改變後父組件監聽到,彈出彈框code

 

 父組件:component

<template>
  <div>
//message爲子控件上綁定的通知;recieveMessage爲父組件監聽到後的方法
    <child2 v-on:message="recieveMessage"></child2>
  </div>
</template>
<script>
  import {Toast} from 'mint-ui'
  export default{
    components: {
      child2: require('./Child2.vue'),
      Toast
    },
    methods: {
      recieveMessage: function (text) {
        Toast('監聽到子組件變化'+text);
      }
    }
  }
</script>

子組件:htm

 

<template>
  <div>
    <input type="text" v-model="msg" @change="onInput">
  </div>
</template>
<script>
  export default{
    data(){
      return {
        msg: '請輸入值'
      }
    },
    methods: {
      onInput: function () {
        if (this.msg.trim()) {
          this.$emit('message', this.msg);
        }
      }
    }
  }
</script>
相關文章
相關標籤/搜索