我正在尝试设置 a 的值Form
基于另一个反应变量中的数据,称为Product
但它似乎不起作用。这Form
应将其值设置为Product
数据如果可用,如果不可用,则使用null
.
这是vue组件代码的一部分:
props: {
ProductID: {
type: Number,
default: null
}
},
setup (props) {
const Product = ref();
async function loadProduct(ProductID) { // Runs when `props.ProductID` changes using a watcher
try {
const Response = await $axios.get(`/api/product/${ProductID}`);
Product.value = Response.data; // This is an array of data
} catch (error) {
console.log(error);
}
}
}
const Form = ref({
ProductTitle: Array.isArray(Product.value) && Product.value[0].producttitle ? Product.value[0].producttitle : null,
ProductText: Array.isArray(Product.value) && Product.value[0].producttext ? Product.value[0].producttext : null,
)}
}
在 vue devtools 中我可以看到Product
填充了数据,但这些值从未分配给Form
键 - 它们只是空的。如果Product
是反应性的,也是如此Form
,为什么这不起作用?
Your Form
仅在以下情况下才初始化setup
是第一次运行,所以它只是初始化但不会更新。如果你想Form
更新时间Product
更新,你可以做到computed
依赖的财产Product
:
const Form = computed(() => ({
ProductTitle: Array.isArray(Product.value) && Product.value[0].producttitle ? Product.value[0].producttitle : null,
ProductText: Array.isArray(Product.value) && Product.value[0].producttext ? Product.value[0].producttext : null,
}))
或者您可以手动更新Form
in loadProduct
,这样每当Product
已重新加载,Form
也将得到更新:
const Form = ref({})
async function loadProduct(ProductID) { // Runs when `props.ProductID` changes using a watcher
try {
const Response = await $axios.get(`/api/product/${ProductID}`);
Product.value = Response.data; // This is an array of data
Form.value = {
ProductTitle: Array.isArray(Product.value) && Product.value[0].producttitle ? Product.value[0].producttitle : null,
ProductText: Array.isArray(Product.value) && Product.value[0].producttext ? Product.value[0].producttext : null,
}
} catch (error) {
console.log(error);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)