繁体   English   中英

如何使用由 API 生成的 URL 在 Vue 中设置背景图像的值

[英]How to set the value of a background Image in Vue using a URL generated by an API

我正在尝试将 Vue 中#app 元素的背景图像的值设置为从 Unsplash 的 API 生成的响应。 我能够检索图像 URL,但在尝试将该信息传递给背景样式元素时遇到了一些困难。

总体而言,我的目标是使用随机图像并在每次重新加载页面时将其显示在屏幕上。

我的方法:

  1. 我从方法部分的 Unsplash API 中拉下了 URL
  2. 然后我在数据部分创建了一个图像并将其设置为等于包含 URL 的响应
  3. 最后,我将模板部分的样式属性设置为:style="image"

这对我不起作用。 我想过使用计算属性,但我什至不知道从哪里开始。

另外,由于我在背景属性上有一个线性渐变,更改图像部分是否会有效地删除背景属性上的线性渐变部分?

如果您能提供任何帮助,将不胜感激! 谢谢

下面,我提供了我的 app.vue 文件

 <template> <div id="app":style="image"> </div> </template> <script> import axios from 'axios' export default { name: 'App', data() { return { image: null, } }, methods: { renderImage: function() { axios.get( 'https://api.unsplash.com/photos/random/?client_id=MY_KEY' ).then(response => { console.log([response.data, response.data.location.title]) this.image = response.data.urls.full }) } }, mounted: function() { this.renderImage() } } </script> <style lang="scss"> #app { background: linear-gradient( to bottom, rgba(245, 246, 252, 0) 45%, rgb(0, 0, 0) 100% ) no-repeat center fixed; background-size: cover; } </style>

按照 Vue文档中的语法,试试这个

 <template>.... <div id="app":style="imageStyleObject">.... </template>

 data() { return { image: '', } }, computed: { // will be re-computed when the image property changes imageStyleObject() { return { backgroundImage: `url(${this.image})`... // insert other styles } } }

关于问题的第二部分,不,我认为没有理由影响线性渐变。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM