【问题标题】:How to set the value of a reactive object (ref) with a value from another reactive object (ref)?如何使用来自另一个反应对象(ref)的值设置反应对象(ref)的值?
【发布时间】:2021-07-21 16:10:09
【问题描述】:

我正在尝试根据另一个名为 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 也是响应式的,为什么这不起作用?

【问题讨论】:

    标签: vue.js vuejs3 vue-composition-api


    【解决方案1】:

    您的Form 仅在setup 首次运行时才被初始化,因此它只是被初始化但不会被更新。如果你想让FormProduct 更新时更新,你可以让它依赖Productcomputed 属性:

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

    【讨论】:

    • 谢谢你的回答很好解释。你能告诉我为什么它会在不使用计算的情况下更新吗?只有在 HTML 元素上使用 v-model 时才会发生反应?
    • Form.value = ... 也可以更新,不一定是v-model
    猜你喜欢
    • 1970-01-01
    • 2019-01-22
    • 2021-03-24
    • 2020-05-19
    • 2021-07-08
    • 2011-12-15
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    相关资源
    最近更新 更多