vue函数中未定义变量



我在vue 3应用程序中使用由组件Mags发出的变量时遇到问题。该变量在importMags函数中工作,但我无法让handleSubmit函数读取/使用它。它总是空的。

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

您的代码片段存在一些问题。

<form @submit.prevent="handleSubmit">

从这一行中,我们期望调用handleSubmit()函数,但它在setup()函数中没有被引用。你已经定义了它,但你也需要返回它

接下来,当您应该在setup((函数的开头声明nowMags时,如下所示:

const nowMags = ref(null)

现在,为了读取或设置任何函数中的nowMags值,必须像nowMags.value = xx = nowMags.valueconsole.log(nowMags.value)那样调用它。

这里有一个代码片段,它应该有助于为您拼凑一些东西。

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
}
};

您在importMags()函数中声明了nowMags。如果希望它在函数外可见,则需要将声明移到那里。

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),

};
},

最新更新