Create reactivity in output by utilizing global functions in Vue

I've recently dived into Vue, along with vue-cli and Single File Components. I'm facing a challenge where I need to have a global function that provides formatted text to components throughout my application. This text should be based on the current settings of that function or class. Whenever these settings change (like the currentKey), all components using this function should automatically update with the new value. In essence: when the currentKey changes, the text in components should reflect the updated return value from the test global function.

This is just a basic example, there might be more complexity involved in reality.

In the provided code snippet, there's a 5-second interval that switches the currentKey variable, altering the output of the test function. My goal is to have all components refreshed every 5 seconds according to this change. I've tried using computed values and other methods but haven't achieved the desired outcome yet.

How can I ensure that components update whenever the currentKey variable is modified?

Vue.component('component1', {
  template: '<div>{{ $test("name") }}</div>',
});

Vue.component('component2', {
  template: '<div>{{ $test("name2") }}</div>',
});

var table = {
  keyone: {
    name: 'TEST NAME FROM FIRST KEY',
    name2: 'TEST NAME 2 FROM FIRST KEY',
  },
  keytwo: {
    name: 'TEST NAME FROM <b>SECOND</b> KEY',
    name2: 'TEST NAME 2 FROM <b>SECOND</b> KEY',
  }
};
var currentKey = 'keyone';

Vue.prototype.$test = function(name) {
  return table[currentKey][name];
};

setInterval(function() {
  if(currentKey == 'keyone')
    currentKey = 'keytwo';
  else currentKey = 'keyone';
  console.log('Key changed to', currentKey);
}, 5000);

new Vue({
    el: '#app',
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <component1></component1>
  <component2></component2>
</div>

Answer №1

Reactivity is fundamental to how objects behave. When an object is made observable, Vue can monitor changes to its properties.

To activate reactivity, simply turn currentKey into a property on an observable object.

If you're using Vue 2.6, you can use Vue.observable directly to make an object reactive. For earlier versions, a dummy Vue instance and the data function are needed for applying reactivity.

Vue.component('component1', {
  template: '<div>{{ $test("name") }}</div>',
});

Vue.component('component2', {
  template: '<div>{{ $test("name2") }}</div>',
});

var table = {
  keyone: {
    name: 'TEST NAME FROM FIRST KEY',
    name2: 'TEST NAME 2 FROM FIRST KEY',
  },
  keytwo: {
    name: 'TEST NAME FROM <b>SECOND</b> KEY',
    name2: 'TEST NAME 2 FROM <b>SECOND</b> KEY',
  }
};

var config = Vue.observable({
  currentKey: 'keyone'
});

Vue.prototype.$test = function(name) {
  return table[config.currentKey][name];
};

setInterval(function() {
  if(config.currentKey == 'keyone')
    config.currentKey = 'keytwo';
  else config.currentKey = 'keyone';
  console.log('Key changed to', config.currentKey);
}, 5000);

new Vue({
    el: '#app',
});
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e0969585a0d2ced6ced1d0">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <component1></component1>
  <component2></component2>
</div>

This example focuses on rendering updates but computed properties will also be triggered, similar to data property changes.

https://v2.vuejs.org/v2/api/#Vue-observable

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

Failure to return an error in the mongoose find function

While attempting to create some statics with Mongoose, I am facing an issue where I cannot access the error argument when using find() or findOne(). Below is my static method: User.statics.authenticate = function(login, password, cb){ return this.mode ...

My intention is to ensure that the page is printed with the Background graphics checkbox pre-checked

When using the print button, I typically include the following code: onclick="window.print();" I also came across this code snippet to set a checkbox as checked by default: <style type="text/css" media="print"> * { -webkit-print-color- ...

What steps should I take to resolve the dynamic image src error in Vuejs?

<img :src="userPhoto" alt="User Photo" /> computed: { userPhoto() { var userImage = this.memberdata.userimage return require(`../../../../php/laravel/token/storage/app/uploads/userimages/${userImage}`); } }, ...

Retrieve information from a website and transfer it to a Google spreadsheet

Despite the wealth of information on this topic, I have yet to find a solution that works for me. My goal is to transfer variables obtained from another website to Google Spreadsheet. These are the variables: var a = parseInt($('table.thinline:eq(4) ...

Moving Rows Between AgGrids

Experimenting with the example provided in this link (Dragging Multiple Records Between Grids) within my React application: https://www.ag-grid.com/react-data-grid/row-dragging-to-grid/ I have some inquiries; How can I retrieve the selected rows for the ...

Conceal HTML elements from the bottom as new content is being added dynamically

I am currently working on a comments feed feature. By default, only the first four comments are displayed, with an option to show more when clicking the "show more" anchor. The issue I'm facing is that if new comments are dynamically added, the CSS hi ...

Obtaining personalized error messages from the backend with express: A step-by-step guide

I'm currently developing a Login App and I'm looking to implement custom error messaging on the Front End. Specifically, I want to display custom error messages when attempting to register with an email that is already in use or when entering a p ...

What does it mean in Javascript when b1 is undefined while o1 has a value and is equal to b1?

Having some issues getting variables to work with drop down options on a page. At first, I couldn't even extract a value from the function but managed to do so by removing "var" from o1. Strange thing is, when I type o1 into the js console on chrome i ...

I attempted to create a callable function for creating a user, but I encountered an error when running it and I am unable to determine the cause

I'm in the process of creating a user management page and have set up a callable function on Firebase to handle the creation of new users. The HTML function I've designed is supposed to update existing users or create new ones. However, when test ...

Vue struggles to handle data coming from a composable function

For my specific case, I need to verify whether the user has subscribed to my product through both Stripe and Firebase. To accomplish this, I created a composable function that checks for the current subscription in the Firebase collection. If the user cur ...

I'm feeling a bit lost with this API call. Trying to figure out how to calculate the time difference between the

Currently, I am working on a project for one of my courses that requires making multiple API calls consecutively. Although I have successfully made the first call and set up the second one, I find myself puzzled by the specifics of what the API is requesti ...

Tips for styling an array of objects using mapping techniques

I have an array of messages and I am currently using the map() function. Each message in the array has two keys - one for the author and another for the message content. What I want to achieve is to change the styles of the div tag when displaying the last ...

When the user clicks on an element, my JavaScript code dynamically updates the CSS property by changing the window

When a tag is clicked in HTML triggering an onclick event, the CSS property that was updated in the JavaScript does not persist. The changes appear momentarily and then disappear once the window is refreshed. Javascript: <script type="text/javascript"& ...

Upgrading React Native hot reloading leads to a complete reload of the application

Recently, I updated my React Native app from version 0.48 to 0.55. Unfortunately, after the upgrade, hot reloading stopped functioning. Any modifications to the files now trigger a complete reload of the app. I have attempted clearing all cache related to ...

Exploring Object Arrays with Underscore.js

Here is an array of objects that I am working with: var items = [ { id: 1, name: "Item 1", categories: [ { id: 1, name: "Item 1 - Category 1" }, { ...

Add HTML content to a specific div according to the option selected in a drop-down menu

I am currently working on a project where I need a button to insert HTML content into a div based on the value selected in a select box. However, the functionality is not working as intended. Upon clicking the button, nothing happens. I am unsure of what t ...

What is the best way to upgrade Angular from version 10 to 12?

Currently tackling an Angular project migration from version 10 to version 12. Unfortunately, the project seems to be encountering issues post-migration and is not running as expected. ...

Using React and Redux to update the state of an object with the current state

Upon mounting my component, I make a call to an API and upon success, the state is updated with the following data: { "brief":"No brief given", "tasks":[ { "_id":"5c74ffc257a059094cf8f3c2", " ...

The message "The property 'layout' is not found on the type 'FC<WrapperProps>' in Next.js" is displayed

I encountered an error in my _app.tsx file when attempting to implement multiple layouts. Although the functionality is working as expected, TypeScript is throwing an error Here is the code snippet: import Layout from '@/components/layouts&apo ...

The FormControlLabel radio button within the RadioGroup is experiencing difficulty in becoming selected

Utilizing a RadioGroup component to showcase a dynamic list of Radio options using FormControlLabel. The dynamic radio choices are appearing correctly on the screen and I can obtain the selected radio option through onChange in RadioGroup. However, after s ...