Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
643 views
in Technique[技术] by (71.8m points)

vue :style 动态绑定style,但是同页面中只要访问接口为什么就会刷新一次?

        <div
          v-for="count in 8"
          :key="count"
          :style="{
            backgroundColor: 'rgb(' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ')'
          }"
          class="contentboxs"
        >

这是页面代码,我现在是循环八次然后用随机数生成给予这八个DIV不同的背景颜色,但是现在问题就是我同页加载时会加载四个接口,然后每加载一次接口这八个DIV的颜色就全部重新更换一次,一进页面就闪好几次颜色这个体验太差啦,不知各位大神有没有解决方法,拜谢~(别的代码块使用tabs标签页切换一次也会更换一次颜色)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

写在模板中只要页面重绘就执行一次肯定会一直在变,解决方案当然是找个地方缓存生成好的颜色数据了
比如生成在data

data() {
  return {
    list: Array.from({length: 8}, () =>
      `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`,
    ),

template

  <div
    v-for="backgroundColor in list"
    :key="backgroundColor"
    :style="{backgroundColor}"
    class="contentboxs"
  >

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...