900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > Vue动态切换背景图

Vue动态切换背景图

时间:2021-07-20 16:59:30

相关推荐

Vue动态切换背景图

最近在改写一个网站,抽离公共组件的时候,发现一个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>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。