Tips for properly passing a Vue3 Ref variable as a reference (plus the mystery of the "global" variable)

I created a custom Quasar/Vue3 component called TemperatureOutside.vue:

<template>
  <div class='text-large-1 text-weight-bold'>
    {{ temperature }}°
  </div>
</template>

<script setup lang='ts'>
import { ref } from 'vue';
import { setupMqtt } from './mqtt';

const temperature = ref(-100)
setupMqtt('temperature', temperature)
</script>

The function setupMqtt is defined in mqtt.ts:

import { connect } from 'mqtt'
import { Ref } from 'vue'

export const setupMqtt = (topic: string, data: Ref): void => {
    const client = connect('mqtt://192.168.10.2:1884')
    const topics = [`dash/${topic}`]
    // removed some irrelevant setup lines
    client.on('message', function (topic: string, message: Buffer) {
      // key line below
      data.value = JSON.parse(message.toString())
    })
}

I intended to pass the data and react to its .value changes in the calling component.

The issue: everything runs smoothly when I comment out the line

setupMqtt('temperature', temperature)
. However, including it triggers this error on the console:

vue-router.mjs:35 [Vue Router warn]: uncaught error during route navigation:
warn @ vue-router.mjs:35
triggerError @ vue-router.mjs:3439
(anonymous) @ vue-router.mjs:3163
Promise.catch (async)
pushWithRedirect @ vue-router.mjs:3157
push @ vue-router.mjs:3089
install @ vue-router.mjs:3520
use @ runtime-core.esm-bundler.js:4349
start @ client-entry.js?t=1663525498443:63
Promise.then (async)
(anonymous) @ client-entry.js?t=1663525498443:82

vue-router.mjs:3441 ReferenceError: global is not defined
...

I am confused about the mentioned global variable and suspect that my attempted reference passing is failing somewhere.

Answer №1

ref() function is used to take an argument and wrap it within a ref object, which includes a .value property that can be reactive. It's important to note that the .value property of a ref object has reactivity.

Would you like to modify the setupMqtt() function found in the TemperatureOutside.vue file as follows:

const outsideTemperature = ref(-100);
setupMqtt('outsideTemp', outsideTemperature.value);

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

Error: Unable to convert undefined or null values to an object - encountered while attempting to run a MySQL query within the router

I have a situation where I am running multiple MySQL queries in a route. The final query is a SELECT statement using the 'email' value retrieved from a previous query as a condition. When testing these 'email' values in MySQL Workbench, ...

Attempted to fetch information using Ajax in Grails

I am attempting to utilize jQuery and ajax with the Grails framework to load the content registration page. However, upon loading the page, I am encountering an issue where the menu and registration fields are duplicated within the page. <script src ...

Order of callback execution in jQuery's ready function

When two JavaScript functions on a page need to be called once the document load is complete, is there a possibility that one function could be executed before the other, or will it always be the same order? For example, using jQuery with the following co ...

Obtaining template attributes in CKEditor: A guide

I have been working with the template plugin in CKEditor to load predefined templates. Each template is defined as follows: templates: [ { title: "Quickclick 1", image: "template1.png", description: "Quickclick 1 template", html_et: "& ...

Issue with form validation, code malfunctioning

I am struggling to figure out why this validation isn't working. Here is the HTML code I'm using: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type='text/javascript' src="scripts. ...

Securing the communication with encrypted API request payloads and responses

It concerns me that all data exchanged between the client and server is in raw json format, as it can easily be manipulated by inexperienced hackers trying to tamper with the values. Although it's not possible to hide a secret salt in javascript, I&a ...

Unable to link to 'Attribute A' because it is not recognized as a valid property of 'Subcomponent'

Within my project, I have a generic class with several components that inherit from it. BaseRdnInput.ts: @Injectable() export abstract class BaseRdnInput implements ControlValueAccessor, Validator { @Input() rdnModel?: any | Array<any ...

Determine the image's position in relation to its parent element while factoring in any vertical offset

Within my HTML, I have arranged two images to sit adjacent to one another. Interestingly, one image happens to be taller than the other. Despite assigning a CSS property of vertical-align: middle to both images, the result is that the shorter image appears ...

Sharing data between controllers within an MVC architecture in JavaScript

I'm currently working on an app using Express and Node. Within my routes, I have '/new-poll' and '/poll-create' //The route poll-create allows users to create a new poll app.route('/poll-create') .get(functi ...

Modifying the response header in a node.js middleware: A step-by-step guide

I've been researching this question extensively on Google, but unfortunately, none of the solutions seem to work for me. The issue I'm facing is related to adding a specific property to the response header called "isAuth," which needs to be set ...

Testing the screen size automatically using Javascript

Hello everyone, I've implemented a JavaScript code that triggers an image to slowly appear and darken the background when a link is clicked. However, on an iPad, the background doesn't completely turn black as intended. The CSS specifies that the ...

Is there a way to mock a keycloak API call for testing purposes during local development?

At my company, we utilize Keycloak for authentication integrated with LDAP to fetch a user object filled with corporate data. However, while working remotely from home, the need to authenticate on our corporate server every time I reload the app has become ...

What is the best way to link multiple select tags in an HTML document?

I am working with a data grid that contains student information such as Name, Class, and Score. Each row has a checkbox for selection. The requirement is that when the user selects one or more rows and clicks on the "show information" Button, a new windo ...

Unable to locate AngularJS controller

As my single controller started to become too large, I decided to split it into multiple controllers. However, when I try to navigate to /signup, I encounter an issue where my UserController cannot be found. The error message states: Error: [ng:areq] Argu ...

Leveraging a component as a property of an object in Vue version 3

I'm trying to figure out if there's a way to use a Component as a property in Vue 3. Consider the TypeScript interface example below: import type { Component } from 'vue' interface Route { url: string icon: Component name: ...

Using JavaScript, iterate over an array to generate input fields and assign values, with the last item in the array pop

I'm working with a div containing the id "inputs" in my HTML file, along with the following JavaScript code: let countries = [ {country: "Honduras", script: `<script src="crazy dog eats drool"> 'cha cha'` }, {country: "Chile", ...

No need to conceal content when switching to another tab if the tab is set to stay in place

My current setup involves using material UI and react-sticky, which has been functioning well. However, I have encountered an issue that I am seeking help with. Here is a link to what I have tried so far. Below are the steps to reproduce this issue: S ...

When rendering, DirectionsRenderer replaces the Marker

I'm currently working on implementing a real-time tracking system for customers to track their deliveries. I have succeeded in setting up markers for the destination and pickup locations, as well as a route path towards them. However, I encountered an ...

Displaying a message indicating no results have been found in the typeahead dropdown using Angular Bootstrap

Is there a way to display a "No Results Found" message in the typeahead search results if no matching data is found? Any suggestions on how to achieve this? See the attached reference screenshot for an example of the message. https://i.sstatic.net/fDpJZ.p ...

Tips for displaying Jinja2 objects from Flask in a draggable list using Vue.js's v-for directive

Here's my Vue code: <div class="drag"> <h2>List 1 Draggable</h2> <draggable id="cat1" v-model="list" :move="checkMove" class="dragArea" :options="{group:'people'}"> <div v-for="element ...