Leveraging external objects in Vue.js computed functions

Can Vue's computed property be used with an external object?

Let's consider the following code example to illustrate the idea:

<!-- Vue file -->

<template>
    <div>{{data.auth}}</div>
</template>

<script>
import {_data} form "./data"

export default {
    computed: {
        data() { return _data }
    }
}
</script>

<!-- data.js file -->

let _auth = "123";

export let _data = {
   auth: _auth
}

setTimeOut(() => _auth = "456", 2000)

Based on this code, one might expect the HTML document to switch from displaying "123" to "456" after 2000ms.

However, it seems that this functionality does not actually work as intended.

Answer №1

When using Vue 3, you have the ability to utilize the ref feature for tracking changes:

import { ref } from 'vue'

const _auth = ref('123')

export const _data = {
    auth: _auth
}

setTimeout(() => {
    _auth.value = '456'
}, 2000)

Here is a snippet that demonstrates this in action:

const _auth = Vue.ref('123')
const _data = {
  auth: _auth
}

setTimeout(() => {
  _auth.value = '456'
}, 2000)

Vue.createApp({
  data() {
    return {
      data: _data
    }
  }
}).mount('#app')
<script src="https://unpkg.com/vue@next"></script>

<div id="app">
  <div>{{ data.auth }}</div>
</div>

Answer №2

Using Observables allows you to create reactive data

import Vue from "vue";

let _auth = "123";
export let _data = Vue.observable({
  auth: _auth
});

setTimeout(() => {
  _data.auth = "456";
}, 2000);

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

Utilizing puppeteer-core with electron: A guide

I found this snippet on a different Stack Overflow thread: import electron from "electron"; import puppeteer from "puppeteer-core"; const delay = (ms: number) => new Promise(resolve => { setTimeout(() => { resolve(); }, ms); }) ...

The download functionality in HTML5 is not functioning properly, so users are forced to rename files when downloading

For weeks, I've been struggling to change the name of the downloaded file. Despite my efforts, instead of being named Chrysanthemum.jpg, it ends up as a hash of the file like 241693260.jpg In my backend setup, I utilize Node.js and Express.js for man ...

Utilizing either Maps or Objects in Typescript

I'm in the process of developing a simple Pizza Ordering App. The concept is, you select a pizza from a list and it's added to a summary that groups all the selections together. Here's how I want it to appear: Pizza Margarita 2x Pizza Sala ...

Passing a Variable Amount of Arguments to a Python Script from Node.js through the Command Line

I have a node server that is responsible for running an external python script using child_process execFile() When I know the exact number of arguments, passing them like this works perfectly fine: const { execFile } = require('node:child_process& ...

JavaScript is throwing an error related to 'typeError' even after explicitly converting to a string

Dealing with JS bugs can be quite frustrating for me. The code snippet below is giving me trouble, as it creates a string containing session data and date information to push into an array: var _writes = String(req.session.subscriber + ":" + req.session.po ...

The process for retrieving an environment variable within a pipeline and transferring it to a release pipeline

My program has an automatic build and deploy process. Here is the current workflow: When I push code to Git, Azure's build pipeline generates an artifact. This artifact is then picked up by Azure's Release pipeline, which deploys it to a Digi ...

The transformation of properties in Django templates and Vue.js using a CDN

I recently completed a small Django project with Vue.js integrated through CDN. This setup utilizes a single server for Django, with Vue.js incorporated into Django templates. The web APIs are sourced from Django Rest Framework (DRF). The project is buil ...

A guide to showcasing JSON data on a webpage using JavaScript

I am currently working on a SOAP WSDL invocation application in MobileFirst. The response I receive from the SOAP WSDL is in JSON format and is stored in the result variable. When trying to access the length of the response using result.length, I encounter ...

Steps to create a Personal Access token on GitHub

I recently developed a test app that utilizes github's graphQL API. I have included the personal access token directly in the code for authentication purposes. However, every time I commit the code with the token, I receive an email from GitHub with t ...

Leveraging a factory value within another factory in AngularJS

Greetings! I am currently working on a web application using AngularJS. Within my project, I have a JavaScript file containing two factories that make HTTP calls to a web API. My goal is to utilize the output of one factory within another factory. Below is ...

Trigger an event in Javascript/ASP.net following a dropdownlist selection

On a single HTML page, I have incorporated three dropdown lists for country, city, and district with an initial blank selected value, along with a Google map. The aim is to automatically center and zoom in on the map whenever users make selections from the ...

Find your favorite artist on Spotify through the search function

Recently, I stumbled upon this intriguing demo showcasing how to search for an artist using the Spotify API. However, despite several attempts, I have been unable to make it function properly. Can anyone provide any tips or guidance on making this work suc ...

Trigger animation once you've scrolled past a designated point in the document

I created a count-up counter animation using JavaScript, but the issue is that the counter starts animating as soon as I refresh the page regardless of where I am on the page or if the counter is even visible. I would like the counter to only start workin ...

Data merging in Firebase 9 and Vue 3 is not functioning properly

I am facing an issue with merging data in my firebase database. I consulted the documentation at https://firebase.google.com/docs/firestore/manage-data/add-data for guidance. After attempting to merge data using setDoc, I encountered an error (Uncaught Ty ...

Creating vibrant squares using HTML and CSS

My objective is to incorporate 3 input options for selecting the color, size, and amount of cubes. The image below showcases my peer's final project, but unfortunately, he refused to share the code with me. We were given a basic template to begin with ...

Securing a namespace using passport js: A step-by-step guide

Imagine I have set up a specific route with the following namespace: app.use('/registered', userRoute); Recently, I wrote the following passportjs function: app.get('/logged/dashboard', function (req, res) { if (req.user === undefi ...

Using Javascript outside of the AngularJS environment

I am trying to utilize Javascript functions outside the controller in Angular JS instead of using a service within a module. Is this allowed? For instance: var UrlPath="http://www.w3schools.com//angular//customers.php" //this section will store all the f ...

Implementing a click event on header elements within a full calendar component in a React application

I'm currently integrating full calendar into my project. I need to implement click events on the header buttons such as prev, next, today, and others. This is how I've set up full calendar with the specified header buttons: <FullCalendar d ...

Guide to combining an Angular 2 application with a Django application

Currently, I have been working through the Tour of Heroes tutorial. The structure of my Django app can be simplified as shown below: apps/my_app/migrations/ apps/my_app/__init__.py apps/my_app/urls.py apps/my_app/views.py frontend_stuff/js/ javascript ...

The content displayed on body.innerHTML does not match the information found in the page source code

Why is the page source newer than the document.body.innerHTML, and how does this happen? While watching a video on YouTube and inspecting the page source in Chrome's console, I noticed that YouTube assigns a unique signature to all videos. Here are t ...