Home > Enterprise >  Variable not defined within vue function
Variable not defined within vue function

Time:11-10

I am having trouble using a variable in a vue 3 app that has been emitted by a component Mags. The variable works in the importMags function, but I cannot get it read/used by the handleSubmit function. It is always null.

<template>
    <form @submit.prevent="handleSubmit">
      <Mags name="magResults"  
      @selectedtags="importMags"> </Mags>
      <q-btn label="Submit" type="submit"  />
    </form>
</template>
<script>
import { ref } from "vue";
export default {
  name: "Name",
 components: { Mags },
  setup() {
    function handleSubmit() {
    console.log(nowMags);
    }

    function importMags(selectedMags) {
      let nowMags = selectedMags;
      return nowMags;
    }
    return {
      importMags,
      nowMags: ref(null),
      selectedMags: ref(null),
    
    };
  },
};
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

There are a few problems with your code snippet.

<form @submit.prevent="handleSubmit">
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

From this line, we are expecting to call the handleSubmit() function, but it is not referenced in the setup() function. You have it defined, but you also need to return it.

Next, when you should declare nowMags at the beginning of the setup() function like so:

const nowMags = ref(null)
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

And now in order to read or set the nowMags value in any function, you must call it like nowMags.value = x or x = nowMags.value or console.log(nowMags.value).

Here's a code snippet that should help piece things together for you.

setup() {
    // Define data variables here
    const nowMags = ref(null)
    const selectedMags = ref(null)
     
    // Define functions here
    const handleSubmit = () => {
      console.log(nowMags.value)
    }
    const importMags(selectedMags) {
      nowMags.value = selectedMags
      return nowMags.value
    }
    
    return {
      nowMags,
      selectedMags,
      importMags,
      handleSubmit
    }
 };
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You declared nowMags inside the importMags() function. If you want it to be visible outside the function, you need to move the declaration there.

 components: { Mags },
  setup() {
    let nowMags; // maybe give it an initial value?

    function handleSubmit() {
    console.log(nowMags);
    }

    function importMags(selectedMags) {
      nowMags = selectedMags;
      return nowMags;
    }
    return {
      importMags,
      nowMags: ref(null),
      selectedMags: ref(null),
    
    };
  },
  • Related