How to solve the initialization error of a certain value of VUE binding array? ~

my data goes like this:

{
   banner:[
     {"Bpic":"b1.jpg","spic":"s1.jpg"},
     {"Bpic":"b2.jpg","spic":"s2.jpg"},
     {"Bpic":"b3.jpg","spic":"s3.jpg"}
   ]
}

template:

that is, there is a picture component that binds the Bpic data of the p _ index item in the data

p_index (showing the number of image indexes) and pageData= {} are defined in data. The problem with
now is that the pageData is empty when the
page is loaded, so the binding of the code on the html will report an error, indicating that the pageData.banner is empty.
in fact, an asynchronous ajax request is invoked in mounted, and the resulting data pageData=res.data assignment. At this time, the bound data is refreshed to the page. Although the actual page is displayed normally, it is still very uncomfortable to report an error in initialization.
currently, I can only specify some data used for page binding when data defines pageData, such as:

data () {
      return {
         pageData: {"banner":[
             {"bpic":"","spic":""}
         ]},
        p_index :0
    }

although the problem is solved
, it always feels a little stupid. I wonder if there is any other more elegant way.

May.05,2022

start with the label.

scenario 1:

<img :src="pageData.banner ? pageData.banner[p_index].Bpic : ''" />

Plan 2:

<img :src="pageData.banner[0] ? pageData.banner[p_index].Bpic : ''" />
export default {
  data(){
    return {
        pageData: {
           banner: []
        }
    }
  }
}

invokes the asynchronous ajax request in created, and then gets the value of the data pageData.


although I don't know why you have to design the data structure in this way, the value of banner list can be given to computed

.
computed: {
    banners () {
        let {banner=[]} = this. pageData;
        return banner || [];
    }
    banner () {
        let {p_index} = this;
        return this.banners[p_index];
    }
}

wrote an example


use computed attributes

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e5b9ce-4411f.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e5b9ce-4411f.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?