Sebastian Rush
Sebastian Rush

Reputation: 538

Vue.js mixin does not work correctly in component

This is my mixin in Vue.js:

var myMixin = {
    data () {
       clockInt: '',        
       clock: '',
       currentTime: new Date()
    },
    mounted () {
       this.intervalSetup();
    },
    methods: {

        intervalSetup () {
           var _this = this;

           // init
           this.getTime();

           // start interval every 60s
           this.clockInt = setInterval(
                _this.getTime(), 60000
           );
        },

        getTime () {
            var now = this.currentTime,
                h = now.getHours(),
                m = now.getMinutes();

            this.clock = h + ':' + m;
        }

    }
};

This should display a simple digital watch which sets the time every 60s.

Then, I register this mixin to Vue, require my component and start a new instance of Vue:

Vue.component('comp', require('./components/MyComponent.vue'));

Vue.mixin(myMixin);

const app = new Vue({
    el: '#app'
});

My component looks like this:

<template>
    <div>{{ clock }}</div>
</template>

<script>
    export default {
        data () {
           return {
               someData: []
           }
        },
        mounted () {

          // call methods

        },
        methods: {

         // some methods

        }
    };
</script>

The first init of the mixin method works fine and as I can see in the Vue dev-tool, all data is present too. But it does not refresh the data in the interval I set up.

Hopefully someone had similar issues and can help me with this.

Upvotes: 1

Views: 4342

Answers (1)

Sebastian Rush
Sebastian Rush

Reputation: 538

Well guys. Both solution work exactly as expected - as a single component and as a mixin. Good to know.

The issue was currentTime: new Date(). The date time was declared in data object only once. So the interval always took this timestamp.

I just removed this and changed var now = new Date(); in my mixin's method.

Thank you guys!

Upvotes: 1

Related Questions