Vue中父組件向子組件通信的方法
Vue是一個輕量級的漸進式框架,對于它的一些特性和優(yōu)點在此就不做贅述。下面通過本文給大家分享Vue中父組件向子組件通信的方法,具體內容詳情如下所示:
props
組件實例的作用域是孤立的。子組件的模板中是無法直接調用父組件的數(shù)據(jù)。
可以使用props將父組件的數(shù)據(jù)傳給子組件。子組件在接受數(shù)據(jù)時要顯示聲明props
看下面的例子
<div id="app">
<panda here='China'></panda>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script>
Vue.component('panda',{
props:['here'],
template:`<div>panda from {{here}}</div>`
})
new Vue({
el: '#app'
})
</script>
頁面上展示的是 panda from China
處理屬性中帶'-‘的問題
Vue是不支持帶杠的寫法的。
如果上述的here變成from-here。需要這樣寫(小駝峰的寫法)
<div id="app">
<panda from-here='China'></panda>
</div>
<script>
Vue.component('panda',{
props:['fromHere'],
template:`<div>panda from {{fromHere}}</div>`
})
new Vue({
el: '#app'
})
</script>
如果需要動態(tài)綁定,需要用到v-bind
<body>
<div id="app">
<panda :here='msg'></panda>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script>
Vue.component('panda',{
props:['here'],
template:`<div>panda from {{here}}</div>`
})
new Vue({
el: '#app',
data:{
msg:'China'
}
})
</script>
</body>
這樣子組件就展示出了父組件的信息(把構造器中的data值傳遞給組件)。而且是動態(tài)綁定(用了v-bind)的。當父組件的data.msg發(fā)生變化的時候。子組件里面的內容也會相應的發(fā)生變化。
注意:props默認是單向綁定:當父組件的屬性變化時,將傳導給子組件,但是反過來不會。這是為了防止子組件無意修改了父組件的狀態(tài)
以上所述是小編給大家介紹的Vue中父組件向子組件通信的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
解決Vue中引入swiper,在數(shù)據(jù)渲染的時候,發(fā)生不滑動的問題
今天小編就為大家分享一篇解決Vue中引入swiper,在數(shù)據(jù)渲染的時候,發(fā)生不滑動的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09
vue獲取當前日期時間(使用moment和new?Date())
在項目開發(fā)中我遇到了日期范圍選擇器,兩種獲取當前日期并做處理的寫法,這里記錄一下,下面這篇文章主要給大家介紹了關于vue獲取當前日期時間(使用moment和new?Date())的相關資料,需要的朋友可以參考下2023-06-06
vue父組件給子組件的組件傳值provide inject的方法
在本篇文章里小編給大家整理的是一篇關于vue父組件給子組件的組件傳值provide inject的方法,需要的朋友們學習下。2019-10-10

