1. 程式人生 > >vue中子元件的拆分 父元件與子元件之間的傳值

vue中子元件的拆分 父元件與子元件之間的傳值

vue是元件式開發,儘量獨立出子元件

prop():父元件傳值給子元件

$emit():子元件傳值給父元件

子元件中的設定: 使用bind

<template>   : default-checked = "check"   @checked="getCurrent" </template> <script> export default { name: ' camelName ',  //name命名採用駝峰式命名, 這裡name定義雖然和後面引用的子元件名沒有關係,但是儘量保持一 致 data () { return {   ......... // 定義引數     },   } props: ['check'], created (){ .......//  生命週期函式,使用this初始化函式 }, method:{    ......       function  getCurrent (param){
    .......   this.$emit('getCurrent', result)  // $emit()將得到的結果result傳入父元件中綁定了getCurrent的函式current中    }    } }, </script> <style scoped>   // scoped的作用是以下的設定只在當前區域生效  ......
</style>

父元件

中引用子元件:

<template>   <camel-name  @getCurrent="current" :check="form.check" ></camel-name>  // 標籤使用元件要用短橫線 </template> <script> import camelNamefrom '../../../../components/file_name'  export default { name: ' camelName1',  //name命名採用駝峰式命名 components: {camelName,....},   //定義子元件 data () { return {   .........//定義引數    form{       check:[],    }     },   } created (){ .......//  生命週期函式,使用this初始化函式 }, method:{    .....  getCurrent (result) {   this.form.check= result   //將從子元件傳過來的結果賦給父元件中的變數用  },  } }, </script> <style scoped>   // scoped的作用是以下的設定只在當前頁面生效  ......
</style>