使用Vue

时间:2017-12-22 20:44:01

标签: javascript vue.js vuejs2 vue-component

我正在构建一个基本的Timer Vue组件。计时器以秒为单位递增,用户可以在点击时播放和暂停计时器。这是组件:

<template>
    <div v-bind:class="{workspaceTimer: isRunning}">
        <a class="u-link-white" href="#" @click="toggleTimer">
            {{ time }}
            <span v-if="isRunning">
                Pause
            </span>
            <span v-else>
                Play
            </span>
        </a>
    </div>
</template>

<script>
    export default {
        props: ['order'],
        data() {
            return {
                time: this.order.time_to_complete,
                isRunning: false,
                interval: null,
            }
        },
        watch: {
            time: function (newTime) {
                this.saveTime()
            }
        },
        methods: {
            toggleTimer() {
                if (this.isRunning) {
                    clearInterval(this.interval);
                } else {
                    this.interval = setInterval(this.incrementTime, 1000);
                }
                this.isRunning = !this.isRunning;
            },
            incrementTime() {
                this.time = parseInt(this.time) + 1;
            },
            formattedTime() {
                var sec_integer = parseInt(this.time, 10);
                var hours   = Math.floor(sec_integer / 3600);
                var minutes = Math.floor((sec_integer - (hours * 3600)) / 60);
                var seconds = sec_integer - (hours * 3600) - (minutes * 60);

                if (minutes < 10) {minutes = "0"+minutes;}
                if (seconds < 10) {seconds = "0"+seconds;}
                this.time = +minutes+':'+seconds;
            },
            saveTime: _.debounce(
                function () {
                    var self = this;
                    axios.put(location.pathname, {time_to_complete: self.time})
                    .then(function (response) {
                        console.log('timer: ' + response.data.time_to_complete);
                    })
                    .catch(function (error) {
                        console.log('Error: ' + error);
                    })
                },
                1000
            )

    }
</script>

我将第二个计数作为一个整数来表示,但是想要将第二个计数显示为mm:ss,并且具有该格式化的值增量,例如00:59增加到1:00。

我可以使用方法或计算属性轻松地格式化我的第二个值(请参阅该示例中的formattedTime()方法),但我不确定如何处理递增该字符串,然后格式化递增串。我是否需要监视对该字符串的更改,然后格式化更新后的字符串?

1 个答案:

答案 0 :(得分:0)

解决了它。答案实际上是在我的组件中使用本地过滤器:

filters: {
    formattedTime: function (value) {
        var sec_num = parseInt(value, 10);
        var hours   = Math.floor(sec_num / 3600);
        var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
        var seconds = sec_num - (hours * 3600) - (minutes * 60);

        //if (hours   < 10) {hours   = "0"+hours;}
        if (minutes < 10) {minutes = "0"+minutes;}
        if (seconds < 10) {seconds = "0"+seconds;}
        return +minutes+':'+seconds;
    }
},

然后将该过滤器应用于我的时间变量:{{ time | formattedTime }}