天天看點

Vue簡單建立一個項目(六)

父子元件之間的傳值

父親傳給兒子:

父親:

<v-home :title="title" :run="run"  :home="this"></v-home>
 data:{title:"zhi"},method:{run(s){alert("hello"+s)}}
           

兒子:

methods:{},props:['title','run','home']
{{title}}
<button @click="run()"><.button>
<button @click="run('simalinjia')"><.button>//傳參的擴充
           

對home的應用,可以給子元件定義一個方法,來調用父元件的一切

兒子的:

methods:{getParentData(){alert(this.home.title);this.home.run()}}
           

父元件給子元件傳值的時候可以驗證合法性:

兒子的:

methods:{},props:['title':String,'run','home':Object]
           

父元件主動擷取子元件的資料和方法:

<v-home ref="son"></v-home>
methods:{
get(){
    this.$refs.son.msg
this.$refs.son.run
      }
}
           

子元件主動擷取父元件的資料和方法:

methods:{
    get(){
        this.$parent.msg
        this.$parent.run
          }
    }