鍍金池/ 問答/HTML/ 如何界定Vue中父組件和子組件

如何界定Vue中父組件和子組件

題目描述

怎么分辨理解Vue組件的相對關系(父組件和子組件)

題目來源及自己的思路

《Vue.js》實戰(zhàn)
組件通過pros屬性接受它的父級的數(shù)據(jù),那么當前這個組件就是相對的子組件了,提供數(shù)據(jù)的就是父組件了。

相關代碼

// 請把代碼文本粘貼到下方(請勿用圖片代替代碼)

<div id="app">
    <my-component message="來自父組件的數(shù)據(jù)"></my-component>
</div>
<script>
    Vue.component('my-component',{
        props:['message'],
        template:`<div>{{message}}</div>`
    })
    var app=new Vue({
        el:'#app'
    })
</script>

你期待的結果是什么?實際看到的錯誤信息又是什么?

props:['message'], 通過這里可以知道m(xù)essage是父組件的數(shù)據(jù),所以my-component相對而言就是子組件了,問題是my-component的父組件是誰呢。。。。
看到
<my-component message="來自父組件的數(shù)據(jù)"></my-component>
就懵了,message這里不是my-component的屬性么?怎么和父組件又有關系呢?

回答
編輯回答
陪她鬧

message 是傳入的 props ,和 state 的作用其實是類似的
這個例子舉的不是很好,#app 上綁定的是最外層的 Vue 實例,包在這個里面的都屬于他的自組件。

父子組件是相對的,不是絕對的。
例如下面的結構,a,b,c 三個 vue 組件,a 包含 b,b 又包含 c,這樣的話 b 又是 a 的子組件,又是 c 的父組件。
在 a.vue 中傳入的 data="data1" 就是傳入到 b.vue 的 props
類比你上面就好比 app 這個變量相當于 a.vue 中的 vue 組件,b 相當于 my-component 這個組件

// a.vue
<template>
    <p>aaaa</p>
    <vue-b data="data1"/>
</template>

// b.vue
<template>
    <p>bbbb</p>
    <vue-c data="data2"/>
</template>

// c.vue
<template>
    <p>cccc</p>
</template>
2017年10月10日 16:35
編輯回答
茍活

你這里的my-component的父組件可以理解為是Vue實例,如果在使用vue-router的情況下,父組件一般是router-view
<my-component message="來自父組件的數(shù)據(jù)"></my-component>
這里的來自父組件的數(shù)據(jù)意思是這里可以填寫來自父組件的數(shù)據(jù),也就是來自他的父組件里data的數(shù)據(jù)

2018年6月11日 20:19
編輯回答
夏夕

父組件不就是app嗎?

我的理解應該是這樣的:

<div id="app">
    <my-component :message="msg"></my-component>
</div>
<script>
    Vue.component('my-component',{
        props:['message'],
        template:`<div>{{message}}</div>`
    })
    var app=new Vue({
        el:'#app',
        data:{
            msg:"Hello World!"
        }
    })
</script>

msg就是來自父組件的數(shù)據(jù),這里的父組件就是Vue當前的實例app。

2017年1月5日 09:30