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

What is the recommended sequence for using decorators in NestJS: @Body(), @Params(), @Req(), @Res()?

How can I properly access the res object to send httpOnly cookies and validate the body with DTO? I keep running into issues every time I attempt it. What is the correct order for these parameters? ...

Extracting Hidden Links: Retrieve the URL that is exclusively visible on the webpage, but not in the source code

While browsing a website, I came across a link that I want to access. However, the link is displayed on the website but is not visible in the HTML file. There is a copy button that allows the link to be copied to the clipboard. I am wondering if anyone k ...

Laravel Mix causing issues with Vue loading when extract() is used

I currently have a simple webpack.mix.js and resources/js/app.js setup in my Laravel project. Here is the code from webpack.mix.js: const mix = require('laravel-mix'); mix.js('resources/js/app.js', 'public/js') .sass(&ap ...

Tips for showcasing a calculated value in vue-table-2

When using an API to retrieve a dataset from a server, the date/time is in epoch format (eventTime). How can I convert this into a human-readable date/time format? What is the correct method for achieving this? Template for displaying table <div class ...

What is the best way to personalize Material UI elements, such as getting rid of the blue outline on the Select component?

Embarking on my journey of developing a React app, I made the decision to incorporate Material UI for its array of pre-built components. However, delving into the customization of these components and their styles has proven to be quite challenging for me ...

Could there be an issue with my function parameters, or is there another underlying problem?

Hey there! I've been working on this function, but it doesn't seem to be running quite right. Here's the code: function chooseCols(colTag, tagName) { // Set column name var column = $('.tagChooser:eq(&apo ...

What is the best way to conceal elements that do not have any subsequent elements with a specific class?

Here is the HTML code I have, and I am looking to use jQuery to hide all lsHeader elements that do not have any subsequent elements with the class 'contact'. <div id="B" class="lsHeader">B</div> <div id="contact_1" class="contac ...

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 ...

Troubleshooting: Angular 2 View not reflecting changes after array push

I have encountered an issue with my two child components. They are both meant to share data from a json file that I load using the http.get/subscribe method. Oddly enough, when I try to push new data into the array, it doesn't seem to update in the vi ...

Modify the color of the div element after an ajax function is executed

My original concept involves choosing dates from a calendar, sending those selected dates through ajax, and then displaying only the chosen dates on the calendar as holidays. I aim to highlight these selected dates in a different color by querying the data ...

Encountering a lack of data in the request body when posting in Express.js

Here are my two attached files. I am encountering an empty response from req.body. Index.html file: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQ ...

Converting an array into an object using Typescript and Angular

I have a service that connects to a backend API and receives data in the form of comma-separated lines of text. These lines represent attributes in a TypeScript class I've defined called TopTalker: export class TopTalker { constructor( pu ...

Utilize JavaScript to reference any numerical value

I am attempting to create a button that refreshes the page, but only functions on the root / page and any page starting with /page/* (where * can be any number). Below is the code I have written: $('.refresh a').click(function() { var pathNa ...

Troubleshooting: jQuery.load function not functioning properly within ASP.NET MVC

I'm facing an issue with my code setup. Currently, I have the following components in different files: @Html.Raw(File.ReadAllText(Server.MapPath("~/Views/Home/index.html"))) This is included in my Razor file. <li><a href="#">Personal Re ...

How can I pass an array object from an HTML form that adheres to a Mongoose schema

I have this HTML form that I'm using to create a new document in my mongo database. The document represents notes given to a teacher based on various criteria. I am storing the notes in an array within the note property, each object containing the aut ...

What is the best way to keep the calendar of a Datepicker always visible while still being able to select a date easily?

When I write my code, the calendar only appears when I press the TextBox. I attempted to place the datepicker in a <div>, but then I was unable to retrieve the selected date. @model Plotting.Models.CalendarModel @using (Html.BeginForm("Calendar", "H ...

Tips for exporting telegram information to a Google spreadsheet

Recently, I set up a basic telegram bot using the telegraf framework and wrote this code snippet to log essential data: bot.on('text', (ctx, next) => { console.log(`[text] ${ ctx.message.chat.id } ${ ctx.from.username } ${ ctx.message.chat.f ...

Is there a way to retrieve the title, description, and image URL of a URL through Ajax, similar to how Facebook shares a link?

Currently, I am developing a project that involves allowing users to submit a URL. The system will then extract the title, images, and description from the provided URL and offer the option to toggle between different images. Upon submission, these extrac ...

What is the correct way to extract results from an Array of Objects in Typescript after parsing a JSON string into a JSON object? I need help troubleshooting my code

Here is my code for extracting data from an array of objects after converting it from a JSON string to a JSON object. export class FourColumnResults { constructor(private column1: string, private column2: string, private column3: string, priv ...

Ways to enlarge image size without compromising the image resolution?

My image is in PNG format or as a blob. It has dimensions of 800px by 600px. However, when I try to resize it using various canvas methods like the one mentioned in this Stack Overflow thread: Resize image, need a good library, it loses quality. I wou ...