The Vue.js mixin is not functioning properly within the component as expected

I've created a mixin in Vue.js for a simple digital watch:

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

        intervalSetup () {
           var _this = this;

           // initialize
           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 mixin should update the time display every 60 seconds.

To use the mixin, I register it to Vue, import my component, and create a new Vue instance:

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

Vue.mixin(myMixin);

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

Here is what my component code looks like:

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

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

          // call other methods here

        },
        methods: {

         // define additional methods here

        }
    };
</script>

The initial setup of the mixin method works fine and the data is present in the Vue developer tools. However, the data does not refresh at the set interval as expected.

If anyone has encountered similar issues or knows how to fix this, I would appreciate your help.

Answer №1

Hey everyone! I'm happy to report that both solutions are working just as intended - whether it's used as a single component or mixin. It's great to have confirmed this.

The main issue I encountered was with the line currentTime: new Date(). By declaring the timestamp in the data object only once, the interval always took the same value.

To resolve this, I simply removed that line and instead included var now = new Date(); within my mixin method.

Thanks a lot for your help!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Explore a vast array of items in a collection

I have a massive collection of various objects that I need to sift through. With over 60,000 elements, the search operation can sometimes be painfully slow. One typical object in this array has the following structure: { "title": "title" "company": ...

The Problem of Unspecified Return Type in Vue 3 Functions Using Typescript

Here is the code snippet I am working with: <template> <div> <ul v-if="list.length !== 0"> {{ list }} </ul> </div> </template> < ...

How to make a HTML div background fill the entire page

Is there a way to extend the background in a div so that it adjusts to fit the screen resolution? I also want to include a navigation bar at the top right corner of this div for the intro page. There will be additional content in other divs positioned be ...

What is the process for downloading files in React from a Node server?

Backend setup for file download: router.get('/download/:fid', filesControllers.downloadFile); Here is the function defined in filesControllers.js to handle file download: const downloadFile = async (req, res, next) => { const fileId = req.p ...

Issue with Phonegap FormData not being sent when using Cross-Origin Resource Sharing (

I have developed a mobile app using phonegap 3.5 and implemented a CORS request in the following manner: function createCORSRequest(method, url, asynchronous) { var xhr = new XMLHttpRequest(); //var n = currentTime.getTime(); var n = 'noc ...

Dynamic updating of Laravel models

I am facing an issue with my website where a series of posts are displayed upon loading, sent to the page using a controller in the following return statement: return View::make('stream')->with($this->postStream()); The postStream functio ...

What is the best way to determine the nearest vertex to a given 3D point?

https://i.sstatic.net/Ooh8W.png Objective: I am aiming to identify the closest vertex to the clicked point. Components Needed: Perspective camera Icosahedron geometry (applied basicmeshmaterial with wireframe) Rotating geometry Raycaster Current Clic ...

What is the correct method for configuring access permissions?

I'm in the process of developing a user management system, but I keep finding myself having to check the user type for each router. router.get('/admin/settings', (req, res) => { if(admin) { //Proceed. } } router.get(&apo ...

How to Utilize Puppeteer for Redirecting Pages While Preserving Cache?

Currently, I am facing a challenge with my code in JavaScript that is responsible for opening a page and logging in. Once Puppeteer finishes the login process, I need it to redirect to another page on the same site without clearing the cache. I attempted ...

How can I store a value or text to track view counts or a counter efficiently?

Recently, I've been trying to implement a view counter on my website, similar to what you see on YouTube. Currently, the number of views stands at 23. I managed to find some code that allows me to increment the view count every time I click on an imag ...

JavaScript: When utilizing 'this' along with nextSibling, encountering the issue of undefined not being an object

When I run a function on the click of a button in my HTML, I want to retrieve the innerHTML value of the sibling element that was clicked. However, I keep receiving the error message 'undefined is not an object'. Here's how my HTML structure ...

The Ajax request was a success, but unfortunately the value in $_POST['value'] is empty

PROBLEM SOLVED The problem appeared to be browser-related. Switched to a different system and the issue was resolved. I am currently working on coding a live search feature that displays user details from a database using ajax and php. The input from t ...

Display the query results on a separate blade

In my original attempt, I intended to display the results in a modal but later decided to show them in a different blade. My goal is to fetch all comments related to a post using its post_id. However, I encountered the following error: The GET method is no ...

Eliminating inline JavaScript code

Hello everyone, I need some help with my website. I have a series of image comparisons and I've currently used inline JS to manage them. However, as the number of comparisons has increased, I realize that inline JS is not the best solution for this. C ...

Instantiate an object within a jQuery click event

Hey there! I have been experimenting with some oojs, attempting to complete a very simple test. If you want to take a look at the code, check it out here: view the test jsbin I realized that I struggled to create a new instance of an object inside a func ...

Ways to ensure a video completely fills the frame

I am experiencing an issue where the video in the main div of my home page does not fully fill the div right away - I have to refresh the page for this to happen. As a result, there is black space on the left and right sides. Interestingly enough, this pr ...

What is the method for adding pages to the ion-nav component in Ionic with Angular?

How can I implement a UINavigationController-like functionality in iOS using an ion-nav element? The example provided here is in Javascript, but I need assistance with implementing it in Angular. Specifically, I'm unsure of how to programmatically add ...

Not entirely certain about how to execute this concept using AJAX

While pondering the development of an instant messaging application, I aimed to decrease the frequency of AJAX requests (currently one every .2s). This led me to devise a unique approach: Initiate an AJAX request from the user side to the server. Wait ...

Transform each element in the array individually

I am seeking a method to transform every element within an array into the format shown below for new users. var userids=['792','796','788','676' etc...] The desired outcome is as follows: var newusers=["792"]["796 ...

Utilize custom fonts from your local directory within a Vite Vue3 project

Inside my main.scss file, I am loading local fonts from the assets/styles/fonts folder: @font-face { font-family: 'Opensans-Bold'; font-style: normal; src: local('Opensans-Bold'), url(./fonts/OpenSans-Bold.ttf) format('truety ...