【问题标题】:Running functions on a data object在数据对象上运行函数
【发布时间】:2015-11-06 05:40:33
【问题描述】:

基本上,当我加载我的主页时,vue.js 会请求一个 api,它会返回一个像这样的 json 响应

[
  {
    "time": 321
  },
  {
    "time": 2712
  }
]

当请求完成加载后,我将数组分配给我的 vue.js 文件中数据对象中的计时器对象。

这就是棘手的地方。所以基本上,当上面加载到 vue 中时,我需要每一个每秒递增一次,使用 setInterval()。更糟糕的是,我需要为每个可以暂停计时器的函数进行另一个回调,并向服务器发送另一个请求(以在服务器端暂停计时器)。 有什么想法吗?

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    我最终创建了一个新计时器,该计时器在文档加载时启动。在响应中,我还添加了一个计数属性(布尔值)。

    new Vue({
        el: "#body",
    
        data: {
            timers: [
                {
                    time: 222,
                    counting: true
                },
                {
                    time: 4123,
                    counting: true
                }
            ],
            test: 2
        },
        methods: {
            pauseTimer: function(timer) {
                timer.counting = !timer.counting;
            }
        },
    
        ready: function() {
            var that = this;
            var timer = setInterval(function(){
                $.each(that.$data.timers, function(index, value){
                    if(value.counting)
                        value.time++;
                });
            }, 1000);
        }
    });
    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    </head>
    <body id="body">
        <ul>
            <li v-repeat="timers">{{ time }} - <a href="#" v-on="click: pauseTimer(this)" v-text="counting ? 'Pause' : 'Start'"></a></li>
        </ul>
        {{ $data | json 2 }}
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.12.10/vue.js"></script>
        
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 2017-06-05
      • 2023-03-28
      • 2020-04-07
      • 2015-04-19
      • 2020-12-03
      • 1970-01-01
      • 2020-10-28
      • 2020-01-22
      • 1970-01-01
      相关资源
      最近更新 更多