如何使用来自另一个反应对象(ref)的值设置反应对象(ref)的值?

How to set the value of a reactive object (ref) with a value from another reactive object (ref)?

我正在尝试根据另一个名为 Product 的反应变量中的数据设置 Form 的值,但它似乎不起作用。如果 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 也是反应性的,为什么这不起作用?

您的 Form 仅在 setup 第一个 运行 时才初始化,因此它仅被初始化但不会更新。如果你想让FormProduct更新的时候更新,你可以让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,
}))

或者您可以在 loadProduct 中手动更新 Form,这样每当 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);
      }
    }
}