最近在改写一个网站,抽离公共组件的时候,发现一个nav组件图标是用background-image显示的。把基本的框架抽离出去,具体菜单项用插槽,然后图片需要用props传参。写了一个小案例。
父组件
Home.vue
<template><div class="home"><button @click="changeBackground">切换图片背景</button><br><br><HelloWorld :bgPath="bgPath"></HelloWorld></div></template><script>import HelloWorld from '@/components/HelloWorld.vue';//import引入图片获得真实的路径import picPath from '@/views/images/seeSee.jpg';import picPath2 from '@/views/images/lai.jpg';export default {name: 'Home',components: {HelloWorld},data() {return {bgPath: picPath}},methods: {//测试切换背景图片changeBackground() {this.bgPath = picPath2;}}}</script>
子组件
HelloWorld.vue
<template><div class="hello" :style="bgStyle"></div></template><script>export default {name: 'HelloWorld',props: {bgPath: {type: String,default: ''},},computed: {//这里可以用计算属性也可以用watchbgStyle() {return {backgroundImage: 'url(' + this.bgPath + ')'}}}}</script><style scoped>.hello {width: 400px;height: 200px;border: 5px solid red;background-repeat: no-repeat;background-size: cover;}</style>