這是一篇學習筆記
一.父子組件傳值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>父子組件傳值</title>
<style>
</style>
<script src="./vue.js"></script>
</head>
<body>
<div id="root">
<counter :count="0" @numberchange="handleChange"></counter>
<counter :count="0" @numberchange="handleChange"></counter>
<div>{{total}}</div>
<validate-content content="hello world"></validate-content>
</div>
<script>
//父組件向子組件傳值用 props ,加:號後傳遞的爲js表達式,示例中則爲數字,不加:號代表的是字符串
var counter = { //局部註冊
props:['count'],
data:function(){//在子組件中定義數據,data不能是對象,必須是一個函數。
return {
number:this.count
}
},
template:'<div @click="handleClick2">{{number}}</div>',
methods:{
handleClick2:function(){
this.number ++;
//this.count++; 父組件可以傳值給子組件,但子組件不可以修改父組件屬性,這裏這麼寫會報錯。
this.$emit("numberchange",this.number);//子組件向父組件傳遞事件,值
}
}
}
var validateContent = {
props:{
//content:[Number,String] //組件參數校驗,可以多選
content:{//組件參數校驗
type:String,
required:true,
default:"default value",
validator:function(value){
return value.length > 5
}
}
},
template:'<div >{{content}}</div>',
}
var vm = new Vue({
el:'#root',
data:{
total:0
},
methods:{
handleChange:function(number){
console.log(number)
// this.total +=1;
}
},
components:{
counter, //局部註冊要在根節點註冊組件
validateContent
}
})
</script>
</body>
</html>
二.父組件向子組件傳遞DOM
先看一個示例
<body>
<div id="root">
<child><p>Qin</p></child>
</div>
<script>
let child = {
template :`<div>
<p>hello world</p>
</div>`
}
var vm = new Vue({
el:'#root',
components:{
child
}
})
</script>
</body>
打開查看器查看一下
發現Qin不見了
<p>Qin</p>
查看官方文檔 ,https://cn.vuejs.org/v2/guide/components-slots.html
我們得出結論:如果 child 沒有包含一個 < slot > 元素,則任何傳入它的內容都會被拋棄
我們加入插槽
<body>
<div id="root">
<child><p>Qin</p></child>
</div>
<script>
let child = {
template :`<div>
<p>hello world</p>
<slot></slot>
</div>`
}
var vm = new Vue({
el:'#root',
components:{
child
}
})
</script>
</body>
發現Qin能正常顯示,且slot將會被替換爲解析後的片段 < p > Qin < /p >
當父組件不向子組件傳值的時候,slot還可以作爲父組件默認值出現
<body>
<div id="root">
<child></child>
</div>
<script>
let child = {
template :`<div>
<p>hello world</p>
<slot>default value</slot>
</div>`
}
var vm = new Vue({
el:'#root',
components:{
child
}
})
</script>
</body>
具名插槽
如果想使用多個插槽,我們先看看效果:
<body>
<div id="root">
<child>
<header>This is header</header>
<footer>This is footer</footer>
</child>
</div>
<script>
let child = {
template :
`<div>
<slot></slot>
<p>Main content</p>
<slot></slot>
</div>`
}
var vm = new Vue({
el:'#root',
components:{
child
}
})
</script>
</body>
發現出現了多個header和footer,要解決這個問題就要用到具名插槽
我們修改代碼如下:
<body>
<div id="root">
<child>
<header slot="header">This is header</header>
<footer slot="footer">This is footer</footer>
</child>
</div>
<script>
let child = {
template :
`<div>
<slot name="header"></slot>
<p>Main content</p>
<slot name="footer"></slot>
</div>`
}
var vm = new Vue({
el:'#root',
components:{
child
}
})
</script>
</body>
可以看到顯示正常了