How to use the slot in Vue
这篇"Vue中的插槽怎么使用"文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇"Vue中的插槽怎么使用"文章吧。
默认插槽
首先做一个页面:
新增 Category.vue
{{title}}分类 {{item}} export default { name: "Category", props:["title","listData"]}.category{ background-color: skyblue; width: 200px; height: 300px;}h4{ text-align: center; background-color: orange;}
App.vue 中使用
import Category from "@/components/Category";export default { name: 'App', components: {Category}, data(){ return{ foods:["火锅","烧烤","小龙虾","牛排"], games:["劲舞团","QQ飞车","超级玛丽","无人深空"], films:["《教父》","《狩猎》","《禁闭岛》","《聚焦》"] } }}.container { display: flex; justify-content: space-around;}
现在修改需求,每个分类都要展示不同的内容:
这里就用到了插槽,修改 Category.vue
{{title}}分类 export default { name: "Category", props:["title"]}.category{ background-color: skyblue; width: 200px; height: 300px;}h4{ text-align: center; background-color: orange;}
修改 App.vue
{{g}} import Category from "@/components/Category";export default { name: 'App', components: {Category}, data(){ return{ foods:["火锅","烧烤","小龙虾","牛排"], games:["劲舞团","QQ飞车","超级玛丽","无人深空"], films:["《教父》","《狩猎》","《禁闭岛》","《聚焦》"] } }}.container { display: flex; justify-content: space-around;}img,video{ width: 100%;}具名插槽
修改 Category.vue
{{title}}分类 这是一些默认值,没有内容时展示 这是一些默认值,没有内容时展示export default { name: "Category", props:["title"]}.category{ background-color: skyblue; width: 200px; height: 300px;}h4{ text-align: center; background-color: orange;}
修改 App.vue
更多美食 {{g}} 单机游戏 网络游戏 经典 热门 推荐 import Category from "@/components/Category";export default { name: 'App', components: {Category}, data(){ return{ foods:["火锅","烧烤","小龙虾","牛排"], games:["劲舞团","QQ飞车","超级玛丽","无人深空"], films:["《教父》","《狩猎》","《禁闭岛》","《聚焦》"] } }}.container,.foot { display: flex; justify-content: space-around;}img,video{ width: 100%;}作用域插槽
如果数据在 Category 中,但需要展示不同的形式,我们可以通过插槽传值,类似于我们从父组件向子组件传值:
{{ title }}分类 export default { name: "Category", props: ["title"], data() { return { games: ["劲舞团", "QQ飞车", "超级玛丽", "无人深空"] } }}.category { background-color: skyblue; width: 200px; height: 300px;}h4 { text-align: center; background-color: orange;}
App 中在子组件中使用 包裹要展示的内容,标签中可以使用scope接收传过来的值
{{ g }} {{ receiveValue.msg }} {{ g }} {{ msg }} {{ g }} {{ msg }} import Category from "@/components/Category";export default { name: 'App', components: {Category},}.container, .foot { display: flex; justify-content: space-around;}img, video { width: 100%;}插槽总结
1.作用:让父组件可以向子组件指定位置插入 html 结构,也是一种组件问通信的方式,适用于父组件==>子组件
2.分类:默认插槽、具名插槽、作用域插槽
3.使用方式:
默认插槽
父组件中:
html结构
子组件中:
插槽默认内容...
具名插槽
父组件中:
html结构1 html结构2
子组件中:
插槽默认内容... 插槽默认内容...
作用域插槽
1.理解:数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定,(games 数据在 Category 组件中,但使用数据所遍历出来的结构由 App 组件决定)
2.具体编码:
父组件中: