【问题标题】:Update data in while loop using VueJS使用 VueJS 在 while 循环中更新数据
【发布时间】:2021-05-24 01:30:57
【问题描述】:

所以我想要的只是在一个方法中使用一个while循环来改变这个对象,我从一个按钮事件中调用它。 我唯一的问题是 cameraPosition 数据在我在循环中递增时不会改变,它只会在函数结束时改变值。

任何帮助将不胜感激!

data() {
  return {
    cameraPosition: { x: 0, y: 0, z: -60 }
  methods: {
    sleep(milliseconds) {
     const date = Date.now();
     let currentDate = null;
     do {
       currentDate = Date.now();
     } while (currentDate - date < milliseconds);
    },

   animation(destinationPos) {
     while (this.cameraPosition.z < destinationPos.z) {
       this.cameraPosition.z = this.cameraPosition.z + 1;
       sleep(200)
   }
  },
 }

【问题讨论】:

    标签: function loops vue.js methods sleep


    【解决方案1】:

    你的睡眠方法被阻塞了。

    使函数异步。 改用这个:

       async animation(destinationPos) {
         while (this.cameraPosition.z < destinationPos.z) {
           this.cameraPosition.z = this.cameraPosition.z + 1;
           await new Promise(r => setTimeout(r, 2000));
       }
    

    https://stackoverflow.com/a/39914235/5671919

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-28
    • 1970-01-01
    • 2018-11-25
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多