Home > Mobile >  How to share variables between functions in Vue
How to share variables between functions in Vue

Time:11-19

I'm learning Vue and trying to test out how I'd pass a user input from one function to another.

My use case is this. I want to take a users input, store it and then supply that to a second function as a variable that it can use to make an API call.

In isolation the two code sections are:

User Input

<div id="v-model-basic" class="demo">
  <input v-model="message" placeholder="edit me" />
  <p>Message is: {{ message }}</p>
</div>

Vue.createApp({
  data() {
    return {
      message: ''
    }
  }
}).mount('#v-model-basic')

API Call

import axios from 'axios';

/* API call for the weather data */
export default {
  name: "Weather",
  data() {
    return {
      weatherList: []
    };
  },
  methods: {
   getweatherData() {
      axios.get("https://anAPIpath.com/that-I-want-to-add-user-input-to").then(response => (this.weatherList = response.data));
    }
  }  
};

Is there a way to do this in Vue where they are both methods within that export function, or is that just the wrong approach? As mentioned, new and learning Vue and I want to ensure I approach this the "Vue way" so things are as neat and tidy as possible.

CodePudding user response:

I see you are doing well, you just need to add the API call to a script tag in the same file and then access the input message like this:

axios.get("https://anAPIpath.com/"  this.message)

CodePudding user response:

Vue has several options for passing variables between components.

props

You can make the variable a prop of the other:

props: {
  message: String
}

The prop is accessed with this.message but it is recommended you copy it to a variable in data and reflect changes with $emit (see documentation link, and $emit section below).

See documentation: https://v3.vuejs.org/guide/component-props.html#props

$emit

You can let a parent component know about the other component's changes with $emit. You can just name an event yourself and pass the value as the first parameter.

this.$emit('messageUpdate', this.message);

See documentation: https://v3.vuejs.org/guide/migration/emits-option.html#emits-option

VueX

With the VueX data storage you can transfer variables from any component across your app to any other.
This takes a little more finess to set up. I suggest going with the above first.

If you are interested (definitely worth to learn), here is the link:
https://vuex.vuejs.org/guide/#getting-started

  • Related