初識插槽
- 一、插槽基本用法
- 二、具名插槽
- 三 編譯作用域
創建專案 vue create slot
配置
重寫src檔案夾

一、插槽基本用法
App.vue
<template>
<div id="app">
app
<Wrap>
<Box />
<div>test</div>
</Wrap>
</div>
</template
<script>
import Wrap from "./components/Wrap";
import Box from "./components/Box";
export default {
components: {
Wrap,
Box,
},
};
</script>
組件 Wrap.vue
<template>
<div class="wrap">
<h1>wrap</h1>
<hr />
<slot /> //這里寫就可以把組件中的內容填充到這里來,不寫里面的內容無效
<hr />
</div>
</template>
組件 Box.vue
<template>
<div class="box">
<h2>Box</h2>
</div>
</template>
二、具名插槽
有時我們需要多個插槽,在向具名插槽提供內容的時候,我們可以在一個 template 元素上使用 v-slot 指令,并以 v-slot 的引數的形式提供其名稱:
代碼如下(示例):
App.vue
當template里面不寫內容的時候就是默認內容,如果有內容默認就不顯示,
<Wrap>
<template v-slot:list>
<h2>默認失效</h2>
</template>
//也可這樣寫
<template #box>
<Box/>
</template>
<template v-slot:footer>
<footer>footer11</footer>
</template>
//默認 寫了之后test1111不會顯示
<template #default>
<h1>test</h1>
</template>
<div>test1111</div>
</Wrap>
Wrap.vue 設定默認顯示的的內容
<slot name="list">
<h1>這里默認的list結構,如果外邊有內容默認的就不顯示</h1>
</slot>
<slot name="box">
<h1>這里默認的box結構</h1>
</slot>
//單標簽
<slot name="footer" />
<slot>
<!-- 默認顯示的值,當外部傳入結構時,不作用 -->
<h1>這是slot的默認結構</h1>
</slot>
三 編譯作用域
官網:父級模板里的所有內容都是在父級作用域中編譯的;子模板里的所有內容都是在子作用域中編譯的,
因為其 (指該插槽的) 內容是傳遞給 組件 的,而不是在組件內部定義的
注意 v-slot 只能添加在 上 (只有一種例外情況),只有需要接收屬性時,v-slot才可以直接寫在組件標簽上 ,
而非父子組件傳值可以用 eventBus
效果圖在最下面
- 就是Box 組件標簽系結的值能在Box組件中獲取
- Box組件中的值要想傳到Wrap也可以用 eventBus
main.js
// Vue原型上 添加 eventBus
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
Vue.prototype.$eventBus = new Vue();
new Vue({
render: h => h(App)
}).$mount('#app')
App.vue
在這個頁面可以獲取到App中的資料
<template>
<div id="app">
app
<Wrap>
<!-- 這里作用域是app組件的 -->
<Box :title="value" />
<p>這是APP的P標簽:{{value}}</p>
</Wrap>
</div>
</template>
<script>
import Wrap from "./components/Wrap";
import Box from "./components/Box";
export default {
components: {
Wrap,
Box,
},
data(){
return {
value:'app-value',
}
}
};
</script>
Wrap.vue
<template>
<div class="wrap">
<h1>wrap</h1>
<h4>接收到Box的資料:{{boxValue}}</h4>
<slot />
<p>這是wrap的P標簽</p>
<hr />
</div>
</template>
<script>
export default {
data() {
return {
value: "warap-value",
boxValue: "",
};
},
created() {
this.$eventBus.$on('send',(value)=>{
this.boxValue=value;
})
},
};
</script>
Box.vue 當點擊按鈕時發送到Wrap組件中
<template>
<div class="box">
<h2>Box</h2>
<p>拿到APP中的tilte : {{ title }}</p>
<input type="text" v-model="boxValue">
<button @click="sendAction">sendToWrap</button>
</div>
</template>
<script>
export default {
props: {
title: String,
},
data() {
return {
boxValue: "",
};
},
methods: {
sendAction(){
console.log(this.boxValue);
this.$eventBus.$emit('send',this.boxValue);
}
},
};
</script>
<style>
.box {
background: yellow;
}
</style>
效果圖:

寫太多了 換下一章講解作用域插槽
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/197667.html
標籤:其他
