Manipulating a global variable in VueJS

Currently, I am referring to Global data with VueJs 2 for my project, focusing on only one variable.

In the code provided, I have included an @click event to update the variable. However, it throws an error stating "Uncaught ReferenceError: $myGlobalStuff is not defined".

Can someone assist in identifying my mistake?

Here is a snippet of the HTML:


<div id="app2">
  {{$myGlobalStuff.message}}
  <my-fancy-component></my-fancy-component>
  <button @click="updateGlobal">Update Global</button>
</div>

And here is the corresponding VueJS code:

var shared = { message: "my global message" }


shared.install = function(){
  Object.defineProperty(Vue.prototype, '$myGlobalStuff', {
    get () { return shared }
  })
}
Vue.use(shared);

Vue.component("my-fancy-component",{
  template: "<div>My Fancy Stuff: {{$myGlobalStuff.message}}</div>"
})
new Vue({
  el: "#app2",
  mounted(){
    console.log(this.$store)
  },
  methods: {
    updateGlobal: function() {
      $myGlobalStuff.message = "Done it!"
      return
    }
  }
})

Minimal changes were made to the existing code, and everything seems to be working fine.

If anyone can point out what I might be missing, it would be greatly appreciated.

Answer №1

Initially, the error message you are encountering is due to not referencing $myGlobalStuff with the usage of this. Simply update it to this:

this.$myGlobalStuff.message = "Done it!"

By making this change, the error should no longer persist.

However, it may not function as expected in terms of reactivity. It seems that what you desire is for the message to be dynamically updated on the page, which wasn't the primary purpose of this code. Originally, it was designed to provide global values to each Vue or component.

To render it reactive, one modification can be made.

var shared = new Vue({data:{ message: "my global message" }})

Once this adjustment is made, the value of message will become reactive.

console.clear()

var shared = new Vue({data:{ message: "my global message" }})

shared.install = function(){
Object.defineProperty(Vue.prototype, '$myGlobalStuff', {
get () { return shared }
})
}
Vue.use(shared);

Vue.component("my-fancy-component",{
template: "<div>My Fancy Stuff: {{$myGlobalStuff.message}}</div>"
})
new Vue({
el: "#app2",
mounted(){
console.log(this.$store)
},
methods: {
updateGlobal: function() {
this.$myGlobalStuff.message = "Done it!"
return
}
}
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3a4c4f5f7a081408140c">[email protected]</a>/dist/vue.js"></script>
<div id="app2">
{{$myGlobalStuff.message}}
<my-fancy-component></my-fancy-component>
<button @click="updateGlobal">Update Global</button>
</div>

This represents a rather simplistic implementation akin to how Vuex functions. As you delve further into this approach, more features of Vuex tend to come into play.

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

Transform your traditional sidebar into a sleek icon sidebar with Semantic UI

I am working on customizing the semantic-ui sidebar. My goal is to have it minimize to a labeled icon when the toggle button is clicked. However, I am having trouble with the animation and getting the content to be pulled when I minimize it to the labeled ...

Could an element's loading be postponed on the initial page a user lands on?

One of my clients has requested a live chat system to be added to their website. I am fully capable of implementing it, and it is included through a script tag. Additionally, they have asked for a slight delay before the chat system loads in. My initial t ...

Vue is lagging behind in implementing Virtual Dom technology

I have come across this code snippet. <template> <div ref="nodesData"> <div v-for="(item, index) in nodes" :key="index" :id="item.id"> {{ item.id }} </div> <div> ...

Having trouble retrieving data from a JSON object that has been stringified. This issue is arising in my project that utilizes Quasar

I successfully converted an excel spreadsheet into a JSON object by using the xml2js parseString() method, followed by JSON.stringify to format the result. After reviewing the data in the console, it appears that I should be able to easily iterate through ...

Adding up the values of an array of objects by month using ReactJS

To start off, I'm using ChartJS and need to create an array of months. Here's how it looks: const [generatedMonths, setGeneratedMonths] = useState<string[]>([]) const [totalValues, setTotalValues] = useState<number[]>([]) const month ...

A step-by-step guide on how to capture user input in Vue.js after the "

Is there a way to capture the character entered after a key is pressed or after the user presses the enter key? I tried using the npm package npm i vue-keypress, but I couldn't figure out how to capture the characters. Can you suggest another method ...

Unlock hidden content with a single click using jQuery's click event

I have a question that seems simple, but I can't quite get the syntax right. My issue is with a group of stacked images. When I click on an image, I want it to move to the front and display the correct description above it. Currently, clicking on the ...

Struggling to grasp the concept of DOM Event Listeners

Hello, I have a question regarding some JavaScript code that I am struggling with. function login() { var lgin = document.getElementById("logIn"); lgin.style.display = "block"; lgin.style.position = "fixed"; lgin.style.width = "100%"; ...

Using Node.js to import modules without the need for assignment

In my recent project, I decided to organize my express application by putting all of my routes in a separate file named routes.js: module.exports = function(server) { // Server represents the Express object server.get('/something', (req, res) ...

Scrolling to an element is not possible when it has both position absolute and overflow-x hidden properties

My issue involves animating ng-view with a slideup animation, requiring absolute positioning of elements and overflow-x: hidden to clip the content. However, I need to use the scrollTo element functionality on one sub-page, which doesn't work when bot ...

Creating visual elements in Vue.js using an array structure

I attempted to use Vuejs to display a list of items, and the code snippet below is a simplified version of my attempt. Despite seeing the data in VueDevTool, I am unable to render it on the page. <template> <div> <h1>{{t ...

Tips for implementing a button redirection to a different page using React

I am facing an issue with a component that includes a function onClick in its Class.propTypes: onClick: PropTypes.func Within another component, I have used this particular component multiple times to populate a page. Each instance of these components con ...

JavaScript encountered an issue as it attempted to reference the variable "button" which was

I am currently working on developing a new API, but I have encountered some issues with JavaScript: Below is my JS/HTML code snippet: const express = require('express'); const app = express(); const PORT = 3000; submit.onclick = function() ...

MUI: Autocomplete cannot accept the provided value as it is invalid. There are no matching options for the input `""`

https://i.stack.imgur.com/KoQxk.png Whenever I input a value in the autocomplete component, an unresolved warning pops up... Here's how my input setup looks: <Autocomplete id="cboAdresse" sx={{ width: 100 + " ...

eliminate empty lines from csv files during the uploading process in Angular

I have implemented a csv-reader directive that allows users to upload a CSV file. However, I have noticed an issue when uploading a file with spaces between words, resulting in blank lines being displayed. Here is an example: var reader = new FileReader ...

What is the method for executing a server-side script without it being transmitted to the browser in any way?

Although the title may be misleading, my goal is to have my website execute a php file on the server side using arguments extracted from the html code. For example: document.getElementById("example").value; I want to run this operation on the se ...

A guide on embedding the flag status within the image tag

I would like to determine the status of the image within the img tag using a flag called "imagestatus" in the provided code: echo '<a href="#" class="swap-menu"><img id="menu_image" src="images/collapsed.gif" hspace = "2"/>'.$B-> ...

Creating Vue3 Component Instances Dynamically with a Button Click

Working with Vue2 was a breeze: <template> <button :class="type"><slot /></button> </template> <script> export default { name: 'Button', props: [ 'type' ], } </scr ...

I wish to substitute a form field with a different one once the value of another field matches a specific condition

The issue I'm facing is that the field disappears once "US" is chosen and does not revert back to the options when another choice is made. teacher_signup.html {% block content %} <h2>Sign Up As Teacher</h2> <form method="post> ...

Guide to importing an npm package into a client-side file

Having some trouble importing the js-search npm package into my client-side .js file. The documentation suggests using import * as JsSearch from 'js-search';, but I keep getting a Uncaught TypeError: Failed to resolve module specifier "js-se ...