Is it possible to access global variables within a composable function?

I am currently in the process of transitioning a project from Vue 2 options API to Vue 3 composition API. Within an options API component, there is a variable named componentData. I am calling a mixin from this component, which allows me to access all the component's variables inside the mixin. Here is an example:

//myMixin.js
export default {
    methods: {
        data_changed() {
            //where componentData is declared in the component
            console.log(this.componentData)
            this.componentData = [1, 2, 3]
        },
    data() {
        return {
            someVar: null
        }
    }
}

However, I am facing difficulties replicating the same behavior with the composition API in Vue 3. Instead of mixins, I am using composables. Consider a scenario where I declare a variable in a component:

import { ref } from 'vue'
import { testData } from '../mixins/useData.js'

export default {
    setup() {
        const componentData = ref([])
        testData()
    }
}

And my composable useData.js:

export function testData() {
    console.log(componentData.value) //undefined
    componentData.value = [1, 2, 3] //will throw error
}

In this case, the composable will output as undefined. How can I access the component's data without passing them as function parameters? Is it because Vue 3 composables are designed to only return a value and do not work the same way as mixins? Can the value of componentData be altered from the composable?

Answer №1

You may choose to pass the ref as a parameter to the function testData():

// useData.js
export function testData(componentData) {
  componentData.value = [1, 2, 3] ✅
}
// MyComponent.vue
import { ref } from 'vue'
import { testData } from '../mixins/useData.js'

export default {
    setup() {
        const componentData = ref([])
                     👇
        testData(componentData)
    }
}

Answer №2

According to the documentation, it is possible! The details can be found in the section on State Management. Here's an excerpt:

While we are utilizing a single reactive object as a store here, you have the option to share reactive state generated using other Reactivity APIs like ref() or computed(), or even retrieve global state from a Composable:

An example of this concept is shown in the following code snippet:

import { ref } from 'vue'

// Global state defined at the module level
const globalCount = ref(1)

export function useCount() {
  // Local state created for each component
  const localCount = ref(1)

  return {
    globalCount,
    localCount
  }
}

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

Activate Click, or Pop-up Box

I've been attempting to log in to the Udemy site using JavaScript, but I'm having trouble triggering the click action on the "log in" link. Unfortunately, the .click() method doesn't seem to be working when I try to select the element. The l ...

Creating custom functions in jQuery and utilizing them within other functions

I have a specific piece of code that I need to execute in two different locations, so I am considering placing it inside a function and calling that function in both places. However, I'm unsure of how to achieve this using jQuery: Could anyone provi ...

Tips for combining a select option and search field into a seamless integrated feature

I'm looking to implement a search field in my project that includes the ability to select specific parameters before running the search. I want it to have a seamless design similar to the image shown below. https://i.sstatic.net/niWP8.png Although I ...

How can I parse a JSON string in a node.js environment?

My current challenge involves sending a JSON string and parsing it on the server-side in node js. The specific value I am trying to extract is the title, but I keep encountering undefined when attempting to parse it. This is my current approach: Home.ejs ...

Please identify the path of chromedriver for selenium-standalone

I've encountered an issue when trying to initialize the selenium-standalone server (https://www.npmjs.com/package/selenium-standalone). The error message I receive is as follows: 14:19:09 /usr/local/lib/node_modules/selenium-standalone/bin/selenium-s ...

Tips for delaying my response in nodejs until the loop is complete

This is the code I'm currently working with: myinsts.forEach(function (myinstId) { Organization.getOrgById(myinstId,function (err, insts) { res.json(insts); }) }); I am using Node.js and encountering an error message that says "Can't set hea ...

Timing interval in Vue for setting and clearing intervals

My Vue.js image slider has been set up to loop through 4 images using a setInterval function. It's almost perfect, but I've noticed that there is a delay when the last image is reached and it resets back to the first image. Is there a way to make ...

How do I retrieve two input values using script code in Ajax?

Currently, I am facing a challenge with implementing two input values in my database search using AJAX. While the script code works well for one input value, it performs poorly with two input values. Below, you will find the codes that I have used. Firstly ...

There was a hiccup in the camera positioning as the tweening began

I've been working on a basic program that involves tweening the camera to a specific position. The functionality works smoothly for the most part, however, I encounter some glitches at the start of the transition when trying to pan the camera using or ...

Guide to profiling resources in Node.js applications

When developing Node.js applications, it's important to keep track of how your code is performing in terms of memory and IO. By monitoring these metrics, you can identify which parts of your code are causing delays or consuming excessive resources. Th ...

Issue with loading the main.css file

Getting Started Managing two domains can be a challenge, especially when trying to make them appear as one seamless website. In this case, I have ownership of and . Goal My goal is to merge the content of https://mauricevandorst.com/personal-page/index ...

Is there a JavaScript method for opening a new window regardless of the PHP file being used?

I have encountered a small dilemma that is causing me frustration. Currently, I have set up a BUTTON on my website. This button, when clicked, triggers a JavaScript function to open a "New Window". The code for this button and function looks like this : ...

Conditional rendering of a component in ReactJS while maintaining the "empty" space

Is there a way to conditionally render a component without affecting the layout of other components? I'm trying to avoid unwanted shifts caused by this div https://i.sstatic.net/g1eUd.gif Do you have any suggestions? Here is a snippet of my code: ...

Establish a connection with a distant socket.io server using a Django server

I am currently facing a challenge in developing a real-time Django application. Due to the limitations of my hosting service, I am unable to run a Websocket server concurrently with my Django server. To enable user-to-user interactions, I took the approac ...

Can someone please explain the purpose of document.reservation.submit();?

As I delve into the code of a previous developer, my focus is on creating a reservation form. After a thorough review, it seems that the only reference to "reservation" is in the name and ID of the form. The form's style includes: display:none ... ...

Having trouble detecting the Selection event of a Dropdown List upon loading

When a user chooses an option from the dropdown menu, I need to capture the selected item and perform an action: $("#user-list").on("change", function() { var selectedUser = $(this).find(":selected").text(); // Perform action with the selected us ...

What is the best way to retrieve the chosen value from a dropdown menu when utilizing a partial view in MVC?

In my current project, I am implementing a partial view to embed one view inside another. The partial view contains a dropdown menu, and I need to retrieve the selected value from that dropdown in order to display another dropdown based on the selection ma ...

Tips on scrolling the web page until the desired web element is visible and carrying out necessary tasks

When searching for input, multiple table data is retrieved. A "show as text link" is present in different table rows that needs to be clicked. I wrote a code that works fine in IE on one machine but does not work on a different machine due to variations i ...

What are the potential causes of an asynchronous error in a WebGLRenderingContext?

While running an animation loop, I encountered a peculiar error message that reads... GL ERROR :GL_INVALID_OPERATION : glDrawElements: Source and destination textures of the draw are the same. This error seems to occur randomly after 2 or 3 animation fr ...

The heroku app was successfully built but encountered an issue with an "Application Error"

After reviewing the build logs on Heroku, I discovered the following: The API endpoint that was requested could not be found. It is important to verify if the correct HTTP verb is being used (such as GET versus POST), and if the desired version is specifi ...