vue slot 插槽使用
如果現(xiàn)在事先模板中不知道需要什么內(nèi)容,需要在使用時傳遞
就可以使用插槽with
來實現(xiàn),這種效果! 類似ThinkPHP中的模板繼承
的block
標簽的功能
匿名插槽
顧名思義就是沒有名字的插槽, 匿名插槽只能有一個
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue study</title>
<script src="node_modules/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<my-comp>
<slot> <p> 這是使用了插槽,如果沒有插槽,這里的內(nèi)容不會顯示 </p> </slot>
</my-comp>
</div>
<!--templates-->
<template id="my">
<div>
<p>其他內(nèi)容</p>
<slot> <span>匿名插槽 -- 默認內(nèi)容</span> </slot>
<p>其他內(nèi)容</p>
</div>
</template>
<!-- JavaScript -->
<script>
// Register Vue Component
let myComp = Vue.extend({
template: '#my',
});
const vm = new Vue({
el: '#app',
data: {
},
components: {
"my-comp": myComp,
},
});
</script>
</body>
</html>
實名插槽
實名插槽可以有多個,在使用時必須使用name屬性來標識
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue study</title>
<script src="./node_modules/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<!--
注意: 這里放的內(nèi)容都是屬于父級的, 所以 @click="fn" 這個fn方
法加在組件中是沒有用的,必須加在 vm 這個實例中
-->
<my-comp>
<div slot="content">
這是在使用時傳入的內(nèi)容...
<a href="" @click="fn"></a>
</div>
</my-comp>
</div>
<!--templates-->
<template id="my">
<div>
<slot name="title">default title</slot>
<slot name="content">default content</slot>
</div>
</template>
<!-- JavaScript -->
<script>
// Register Vue Component
let myComp = Vue.extend({
template: '#my',
});
const vm = new Vue({
el: '#app',
data: {
},
methods: {
fn () {
alert("hello");
}
},
components: {
"my-comp": myComp,
},
});
</script>
</body>
</html>
插槽可以設置默認值,定義了不使用就會使用默認值,
如果沒有名字的標簽的標簽默認會放到default(即匿名插槽)