vue computed属性设置css背景图片

前端萌新第一次提问
我给div动态绑定了一个style 就是利用计算属性随机显示背景图片
<div calss="login" :style="backgourndStyle">

computed:{
            backgourndStyle: function() {
                // 计算body可用高度
                let cHeight = window.outerHeight - (window.outerHeight - window.innerHeight);
                // 计算背景图
                let imgs = ["../assets/img/background1.jpg","../assets/img/background2.png"];
                let imgName = imgs[Math.floor(Math.random() * 2)];
                let style = "background-image:url(" + imgName + "); background-repeat: round; height:" + cHeight + "px;";
                return style;
            }
        },

但是图片总是显示不出来
image.png
console也不报错误
image.png

这是为什么呢?

阅读 5.6k
3 个回答

require,或者文件放到static文件夹下,直接 '/static/...'

动态加载图片如果不是http/https开头的 需要使用requie/import导入 才能引用到图片

加这一行代码试试let imgs = imgPaths.map(path => require(path));

computed: {
    backgourndStyle: function() {
        let imgPaths = ["../assets/img/background1.jpg","../assets/img/background2.png"];
        let imgs = imgPaths.map(path => require(path));  // 加这一行代码
        let imgName = imgs[Math.floor(Math.random() * 2)];
        let style = "background-image:url(" + imgName + "); background-repeat: round; height:" + cHeight + "px;";
        return style;
    }
},
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题