1. 程式人生 > 實用技巧 >Vue中的元件傳值

Vue中的元件傳值

1.父傳子

通過props傳值
語法:v-bind:子元件props中的變數名= “父元件中的data中定義的資料”

  • 父元件:
Vue.component('Father',{
    template: '#father',
    data () {
      return {
        money: 2000
      }
    }
  })
  • 子元件:通過props['value'] 接收父元件傳遞過來的資料,相當於在data中定義了,可以直接使用
Vue.component('Son',{
    template: '#son',
    // props: ['money']
    // props: { //屬性校驗
    //   money: Number
    // }
      props: {
        money: {
          validator (val) {
           
            return val > 3000
          }
        }
      }
  })

2.子傳父

  • 父元件:<Child @receive= 'receive'/>
  • 子元件:this.emit('receive','傳遞的資料')

3.兄弟元件傳值

  • 通過vuex進行傳值
  • 通過事件匯流排 let eventBus = new Vue()
//兄弟1:
methods:{
  函式名{
   eventBus.emit('自定義事件名',傳的資料)
   }
}

//兄弟2:
created(){
   eventBus.$on('兄弟1傳送的自定義的事件名',回撥函式)//對資料進行接收
}
兄弟2: