# 組件訪問(了解)
組件訪問指的是嵌套組件之間,會形成父子組件。子組件可以用 `this.$parent` 訪問父組件,父組件可以用 `$children` 訪問子組件。
>[warning] 減少使用 `$parent` 和 `$children`它們的主要目的是作為訪問組件的應急方法。
> 推薦用 props 和 events 實現父子組件通信
## 父組件訪問子組件兩種方式
`$children`和`$refs` 這兩種方式推薦用后者。
```
var vm = new Vue({
el: "#app",
data: {
txt: '456'
},
mounted() {
console.log(this.$refs.ym.$options.propsData.msg)
}
})
```
>[danger] ### $children的缺陷:
> 通過$children訪問子組件時,是一個數組類型,訪問其中的子組件必須通過索引值。
> 但是當子組件過多,我們需要拿到其中一個時,往往不能確定它的索引值,甚至還可能會發生變化。
> 有時候,我們想明確獲取其中一個特定的組件,這個時候就可以使用$refs
>[success] ### $refs的使用:
> $refs和ref指令通常是一起使用的。
> 首先,我們通過ref給某一個子組件綁定一個特定的sign(標識)。
> 其次,通過this.$refs.sign就可以訪問到該組件了。
## 子組件訪問父組件
`$parent`
```
Vue.component('ym-alert', {
props: ['msg'],
template: ` <div class="alert alert-danger">{{msg}} <ym-abc></ym-abc></div>`,
mounted() {
console.log(this.$parent.txt = 789)
}
});
```
>[danger] 盡管在Vue開發中,我們允許通過$parent來訪問父組件,但是在真實開發中盡量不要這樣做。
> 子組件應該盡量避免直接訪問父組件的數據,因為這樣耦合度太高了。
> 如果我們將子組件放在另外一個組件之內,很可能該父組件沒有對應的屬性,往往會引起問題。
> 另外,更不好做的是通過$parent直接修改父組件的狀態,那么父組件中的狀態將變得飄忽不定,很不利于我的調試和維護。
## 訪問根組件
`$root`
```
Vue.component('ym-abc', {
template: `<div>2252522</div>`, mounted() {
console.log(this.$root)
this.$root.txt = 7816196
}
})
```
>[danger] $root的問題與$parent很類似。不再贅述,不建議使用
## 代碼
```
<div class="container" id="app">
{{txt}}
<ym-alert ref="ym" msg="123"></ym-alert>
</div>
<script src="js/vue.js"></script>
<script>
Vue.component('ym-abc', {
template: `<div>2252522</div>`, mounted() {
console.log(this.$root)
this.$root.txt = 7816196
}
})
Vue.component('ym-alert', {
props: ['msg'],
template: ` <div class="alert alert-danger">{{msg}} <ym-abc></ym-abc></div>`,
mounted() {
//console.log(this.$parent.txt = 789)
}
});
var vm = new Vue({
el: "#app",
data: {
txt: '456'
},
mounted() {
console.log(this.$refs.ym.$options.props.msg)
}
})
</script>
```