當子組件做循環,或者某一部分dom結構應該由外部傳遞進來的時候用作用域插槽。
作用域插槽必須是template開頭且結尾
slot-scope以及對應的自定義名字(這裏是myprops)來接收傳遞過來的數據:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="./vue.js"></script>
<!-- <script src="http://cdn.staticfile.org/vue/2.6.10/vue.common.dev.js"></script> -->
</head>
<body>
<div id="root">
<child>
<!-- 作用域插槽必須是template開頭且結尾 -->
<template slot-scope="myprops">
<li>{{myprops.item}}</li>
</template>
</child>
</div>
<script type="text/javascript">
Vue.component("child", {
data: function() {
return {
list: [1, 2, 3, 4, 5, 6]
}
},
template: `<div>
<ul>
<li v-for="item of list">{{item}}</li>
</ul>
<ul>
//這種方式的作用是:顯示什麼,怎麼顯示不再是子組件決定了,而是父組件調子組件的時候給子組件傳遞模版:
<slot v-for="item of list" :item=item></slot>
</ul>
</div>`
});
var vm = new Vue({
el: "#root"
})
</script>
</body>
</html>