Some pits of vue2 binding inline style background

At this point, I have a requirement to add a background image to a box. This background image is dynamically requested, so what should I do? It seems simple, but in fact, it is very important to postgraduate the basic knowledge of JavaScript and the understanding of the vue life cycle.
The normal vue inline style is written as follows:

<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
data: {
  activeColor: 'red',
  fontSize: 30
}

At this time, the style is bound to a JavaScript object. "-" is not allowed in JavaScript, so the binding of a background image should be written as follows:

<div :style="{background: 'url('+ img +')',backgroundSize:cover }"></div>
data:{
  img:'xxx.png'
}

Well, the background image has been successfully added by string splicing, and we changed it to dynamic request.

<div :style="{background: 'url('+ img +')',backgroundSize:cover }"></div>
data:{
    img:'xxx.png'
},
methods:{
// 伪代码 请求数据
      getImg(){
        this.$http.get().then(function (e) {
          this.img = e.data //将数据赋值给img
        }.bind(this))
      }
},
created(){
// 调用函数
    this.getImg()
}

The created vue2 lifecycle hook function
is called synchronously after the instance is created. At this point the instance has finished parsing options, which means that it has established: data binding data, computed properties, methods, watcher/event callbacks.
At this point you will find that although it is rendered, it reports an error

Error in render function
Cannot read property 'img' of undefined

Because it is a virtual dom before the life cycle is mounted, that is to say, when the page has been rendered, but the vue has not been executed, all data is lost. At this time, we add

<div v-if='img ' :style="{background: 'url('+ img +')',backgroundSize:cover }"></div>

Indicates that when there is an img attribute, we select this element, and the background image is successfully bound.



Author: Yu cccc
Link: https://www.jianshu.com/p/57d913f50439
Source: Jianshu The
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325906824&siteId=291194637