slot 插槽
- 给组件预留地方以后加内容 旧 slot slot-scope 新 v-slot
1. slot
① 留一块地方:
html结构:
<div id="app">
<Hello>
<div>
这里是1903
</div>
</Hello>
</div>
<template id="hello">
<div>
<slot></slot>
<h3>这里是hello</h3>
</div>
</template>
Vue.component('Hello', {
template: '#hello'
})
js结构:
Vue.component('Hello', {
template: '#hello'
})
new Vue({
el: '#app'
})
② 给slot加name属性
html结构:
<div id="app">
<Hello>
<header slot='header'> 这里是头部 </header>
<footer slot='footer'> 这里是底部 </footer>
</Hello>
</div>
<template id="hello">
<div>
<slot name = "header"></slot>
<h3>这里是hello</h3>
<slot name = "footer"></slot>
</div>
</template>
js结构:
Vue.component('Hello', {
template: '#hello'
})
new Vue({
el: '#app'
})
2. slot-scope
html结构:
<div id="app">
<Hello>
<template slot="default" slot-scope="slotProp">
<p> {{ slotProp.msg }} </p>
</template>
</Hello>
</div>
<template id="hello">
<div>
<slot name = "default" :msg = "msg"></slot>
</div>
</template>
js结构:
Vue.component('Hello', {
template: '#hello',
data() {
return {
msg: 'hello'
}
}
})
new Vue({
el: '#app'
})
3.v-slot
① 不需要数据
html结构:
<div id="app">
<Hello>
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>
<template v-slot:footer>
<p>Here's some contact info</p>
</template>
</Hello>
</div>
<template id='hello'>
<div class="container">
<header>
<!-- 我们希望把页头放这里 -->
<slot name = "header"></slot>
</header>
<main>
<!-- 我们希望把主要内容放这里 -->
<p>A paragraph for the main content.</p>
<p>And another one.</p>
</main>
<footer>
<!-- 我们希望把页脚放这里 -->
<slot name = 'footer'></slot>
</footer>
</div>
</template>
js结构:
Vue.component('Hello', {
template: '#hello'
})
new Vue({
el: '#app',
data: {
msg: '<h3> hello 1903</h3>'
}
})
② 需要数据
html结构:
<div id="app">
<Hello>
<template v-slot:default = "slotProp">
{{ slotProp.msg }}
</template>
</Hello>
</div>
<template id="hello">
<div>
<slot name = "default" :msg = "msg"></slot>
</div>
</template>
js结构:
new Vue({
components: {
'Hello': {
template: '#hello',
data () {
return {
msg: 'hello'
}
}
}
}
}).$mount('#app')
属性验证
-
用props拿到的数据要进行验证
-
验证失败会在浏览器控制台报错,但不会影响数据的使用
-
props: [ ‘msg’ ] 没有进行验证,知识单纯的接收了一个父组件传递来的数据
-
props: { attr: attrType } 进行普通属性验证
-
props: { type: typeType, default: value } 这里的default是为这个属性设置初始值
-
props: { validator ( val ) { return boolean }} 可以进行一个条件的比较
-
html结构:
<div id="app">
<Father></Father>
</div>
<template id="father">
<div>
<h3> 这里是父组件 </h3>
<Son :money = "money" :n = "n"></Son>
</div>
</template>
<template id="son">
<div>
<h3> 这里是子组件 </h3>
<p> 父亲给了我 {{ money + 100}} 钱 </p>
<p> num: {{ num }} </p>
</div>
</template>
js结构:
Vue.component('Father', {
template: '#father',
data() {
return {
money: 1000,
n: 400
}
}
})
Vue.component('Son', {
template: '#son',
props: { // key: value key就是我们接收的属性 value就是我们想要的这个属性的数据类型
'money': Number, // String Boolean Object...
'n': {
validator(val) { //属性验证函数,一般常用于条件的比较
// val 就是我们得到的数据
return val > 300 //返回值是一个布尔值
}
},
'num': {
type: Number,
default: 200
}
}
})
new Vue({
el: '#app'
})