在app.vue里使用组件Category
<template>
<div class="container">
<Category title="美食" :listData="foods">
<img src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt="图片加载错误">
</Category>
</div>
</template>
<Category> 添加一个img </Category>
如果不使用插槽的方式在Category中定义,虽然vue会解析这个img,但是它并不知道要往哪里放这个东西。还是不会展示:
往Category里加入标签<slot></slot>
<template>
<div class="category">
<h3>{{title}}</h3>
<!-- 定义一个插槽,组件的使用者来进行填充 -->
<slot>默认文字,不传递时会展示</slot>
</div>
</template>
就能把图片放到想要的位置 如果不传递时将会展示标签内部写的东西。
完整Demo如图所示:
App.vue代码:
<template>
<div class="container">
<Category title="美食">
<img src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt="加载错误">
</Category>
<Category title="游戏">
<ul>
<li v-for="(game,index) in games" :key="index">{{game}}</li>
</ul>
</Category>
<Category title="电影">
<img src="http://47.103.203.112:8080/mydemo/image/102.JPG" alt="加载错误">
</Category>
</div>
</template>
<script>
import Category from './components/Category.vue'
export default {
name:'App',
components: {Category},
data(){
return{
foods:['烧烤','火锅','牛排'],
games:['动作','休闲','冒险'],
films:['中国','美国','非洲'],
}
}
}
</script>
<style scoped>
.container{
display: flex;
justify-content: space-around;
}
</style>
Category.vue代码:
<template>
<div class="category">
<h3>{{title}}</h3>
<!-- 定义一个插槽,组件的使用者来进行填充 -->
<slot>默认文字,不传递时会展示</slot>
</div>
</template>
<script>
export default {
name: 'Category',
props: ['title']
}
</script>
<style scoped>
.category{
background-color: skyblue;
width: 200px;
height: 300px;
}
h3{
text-align: center;
background-color: orange;
}
video{
width: 100%;
}
img{
width: 100%;
}
</style>
main.js代码:
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//关闭Vue的生产提示
Vue.config.productionTip = false
//创建vm
new Vue({
el: '#app',
render: h => h(App),
beforeCreate() {
Vue.prototype.$bus = this
},
})