30no2's Blog.

vue.js笔记四

字数统计: 651阅读时长: 3 min
2021/05/25 Share

一、slot插槽

1、基本使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<div id="app">
<div>{{ message }}</div>
<cpn><span>hehe</span></cpn>
<cpn><button>hehe</button></cpn>
</div>
<template id="cpn">
<div>
<h2>测试</h2>
<slot></slot>
</div>
</template>
<!--导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script>
<script>
const app = new Vue({
el:'#app',
data:{
message:"hello vue"
},
components:{
cpn:{
template:`#cpn`
}
}
});
</script>

2、默认值

  • 如果设定了默认值,则当没有值的时候,显示默认值,并且可以通过name属性修改某个默认值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<div id="app">
<div>{{ message }}</div>
<cpn><span slot="left">sss</span></cpn>
</div>
<template id="cpn">
<div>
<h2>测试</h2>
<slot name="left">左边</slot>
<slot>中间</slot>
<slot>右边</slot>
</div>
</template>
<!--导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script>
<script>
const app = new Vue({
el:'#app',
data:{
message:"hello vue"
},
components:{
cpn:{
template:`#cpn`
}
}
});
</script>

3、作用域

  • 插槽中的数值在自己作用域中表示
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<div id="app">
<div v-show="isShow">{{ message }}</div>
<npc></npc>
</div>
<template id="npc">
<div>
<h2 v-show="isShow">hhhh</h2>
</div>
</template>
<!--导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script>
<script>
const app = new Vue({
el:'#app',
data:{
message:"hello vue",
isShow: true
},

components:{
npc:{
template:`#npc`,
data(){
return {
isShow:false
}
}
}
}
});
</script>

4、子插槽传递数值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<div id="app">
<div>{{ message }}</div>
<cpn>
<!-- 目的是获取子组件中的planguage-->
<template slot-scope="slot">
<!-- <span v-for="item in slot.data">{{item}}-</span>-->
<span>{{slot.data.join(' - ')}}</span>
</template>
</cpn>
</div>
<template id="cpn">
<div>
<!-- 通过:data属性将planguage传递给父值 data名字可以随便取-->
<slot :data="planguage">
<ul>
<li v-for="item in planguage">{{item}}-</li>
</ul>
</slot>
</div>

</template>
<!--导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script>
<script>
const app = new Vue({
el:'#app',
data:{
message:"hello vue"
},
components:{
cpn:{
template:`#cpn`,
data(){
return {
planguage:['no1','no2','no3']
}
}
}
}
});
</script>
CATALOG
  1. 1. 一、slot插槽
    1. 1.1. 1、基本使用
    2. 1.2. 2、默认值
    3. 1.3. 3、作用域