vue 父子組件傳參


父向子組件傳參

  例子:App.vue為父,引入componetA組件之后,則可以在template中使用標簽(注意駝峰寫法要改成componet-a寫法,因為html對大小寫不敏感,componenta與componentA對於它來說是一樣的,不好區分,所以使用小寫-小寫這種寫法)。而子組件componetA中,聲明props參數’msgfromfa’之后,就可以收到父向子組件傳的參數了。例子中將msgfromfa顯示在<p>標簽中。
App.vue中

 

1
1<component-a msgfromfa= "(Just Say U Love Me)" ></component-a>

  

1
2
3
4
5
6
7
8
mport componentA  from  './components/componentA'
export  default  {
new  Vue({
components: {
componentA
}
})
}

  


componentA.vue中 

 

1
<p>{{ msgfromfa }}</p>

  

1
2
3
export  default  {
props: [ 'msgfromfa' ]
}

  

 

父向子組件傳參(.$broadcast)

  用法:vm.$broadcast( event, […args] )廣播事件,通知給當前實例的全部后代。因為后代有多個枝杈,事件將沿着各“路徑”通知。
  例子:父組件App.vue中<input>綁定了鍵盤事件,回車觸發addNew方法,廣播事件”onAddnew”,並傳參this.items。子組件componentA中,注冊”onAddnew”事件,打印收到的參數items。
App.vue中

<div id="app">
<input v-model="newItem" @keyup.enter="addNew"/>
</div>
export default {
new Vue({
methods: {
addNew: function() {
this.$broadcast('onAddnew', this.items)
}
}
})
}

 



componentA.vue中

1
2
3
4
5
6
7
8
import componentA  from  './components/componentA'
export  default  {
events: {
'onAddnew' : function(items){
console.log(items)
}
}
}

  

子組件向父傳參(.$emit)

  用法:vm.$emit( event, […args] ),觸發當前實例上的事件。附加參數都會傳給監聽器回調。
  例子:App.vue中component-a綁定了自定義事件”child-say”。子組件componentA中,單擊按鈕后觸發”child-say”事件,並傳參msg給父組件。父組件中listenToMyBoy方法把msg賦值給childWords,顯示在<p>標簽中。
App.vue中

<p>Do you like me? {{childWords}}</p>
<component-a msgfromfa="(Just Say U Love Me)" v-on:child-say="listenToMyBoy"></component-a>

 

import componentA from './components/componentA'
export default {
new Vue({
data: function () {
return {
childWords: ""
}
},
components: {
componentA
},
methods: {
listenToMyBoy: function (msg){
this.childWords = msg
}
}
})
}

 


componentA.vue中 

<button v-on:click="onClickMe">like!</button>

 

import componentA from './components/componentA'
export default {
data: function () {
return {
msg: 'I like you!'
}
},
methods: {
onClickMe: function(){
this.$emit('child-say',this.msg);
}
}
}

 

子組件向父傳參(.$dispatch)

  用法:vm.$dispatch( event, […args] ),派發事件,首先在實例上觸發它,然后沿着父鏈向上冒泡在觸發一個監聽器后停止。
  例子:App.vue中events中注冊”child-say”事件。子組件componentA中,單擊按鈕后觸發”child-say”事件,並傳參msg給父組件。父組件中”child-say”方法把msg賦值給childWords,顯示在<p>標簽中。
App.vue中

<p>Do you like me? {{childWords}}</p>
<component-a msgfromfa="(Just Say U Love Me)"></component-a>

 

import componentA from './components/componentA'
export default {
new Vue({
events: {
'child-say' : function(msg){
this.childWords = msg
}
}
})
}

 


componentA.vue中 

<button v-on:click="onClickMe">like!</button>
import componentA from './components/componentA'
export default {
data: function () {
return {
msg: 'I like you!'
}
},
methods: {
onClickMe: function(){
this.$dispatch('child-say',this.msg);
}
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM