(1)父組件通過ref獲取子組件data
- 給子組件模板一個(gè)ref名
- 父組件通過this.$ref.ref名.data來取子組件的數(shù)據(jù)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ref父組件訪問子組件數(shù)據(jù)</title>
<script type="text/javascript" src="https://cdn.bootcss.com/vue/2.5.3/vue.min.js"></script>
</head>
<body>
<div id="app">
<button @click="getChildInfo">通過ref獲取子組件實(shí)例</button>
<h3>{{message}}</h3>
<component-a ref="child"></component-a>
</div>
<script>
Vue.component('component-a',{
template:"<div>{{message}}</div>",
data:function(){
return {
message:"子組件的信息"
}
}
});
var app = new Vue({
el:"#app",
data:function(){
return {
message:""
}
},
methods:{
getChildInfo:function(){
this.message = this.$refs.child.message;
}
}
});
</script>
</body>
</html>
image.png
可用來調(diào)用子組件的方法
(2)為父組件做替補(bǔ)的slot插槽
- 父組件模板里殖卑,插入在子組件標(biāo)簽內(nèi)的所有內(nèi)容將替代子組件slot標(biāo)簽及它的內(nèi)容
- 當(dāng)slot的個(gè)數(shù)大于父模板插入的內(nèi)容數(shù)目,依然全部渲染為父模板內(nèi)容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>slot插槽</title>
<script type="text/javascript" src="https://cdn.bootcss.com/vue/2.5.3/vue.min.js"></script>
</head>
<body>
<div id="app">
<in-case>
<p>我是先發(fā)全明星控衛(wèi)保羅!</p>
</in-case>
</div>
<script>
Vue.component('in-case',{
template:`<div>
<slot><p>我是替補(bǔ)控衛(wèi)貝弗利地獄惡狗</p></slot>
</div>`
})
var app = new Vue({
el:"#app"
})
</script>
</body>
</html>
image.png
(3)父向子傳值props
可以使用數(shù)組或?qū)ο蠖杳郏瑯?biāo)準(zhǔn)情況使用對(duì)象
image.png
(4)子向父?jìng)髦祎his.$emit()
子組件方法中調(diào)用
this.$emit('觸發(fā)綁定在子組件上的方法'嫉父,傳遞給父組件的數(shù)據(jù))
(5)provide / inject
一個(gè)組件使用了 provide 向下提供數(shù)據(jù),那其下所有的子組件都可以通過 inject 來注入氛什,不管中間隔了多少代朴上,而且可以注入多個(gè)來自不同父級(jí)提供的數(shù)據(jù)秦踪。需要注意的是机错,一旦注入了某個(gè)數(shù)據(jù)爬范,比如上面示例中的 app,那這個(gè)組件中就不能再聲明 app 這個(gè)數(shù)據(jù)了弱匪,因?yàn)樗呀?jīng)被父級(jí)占有青瀑。