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标签页切换一次也会更换一次颜色)

阅读 2.3k
2 个回答

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

贴完整代码吧,你这个看不出来,大概是数据变了,重新render了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题