简体   繁体   English

基于标志的 Nuxtjs Vue3 反应性

[英]Nuxtjs Vue3 reactivity based on a flag

I created a simple Page in Nuxt which would use a boolean variable to switch between a Detail component and a Form component.我在 Nuxt 中创建了一个简单的页面,它将使用 boolean 变量在 Detail 组件和 Form 组件之间切换。

<script setup>
definePageMeta({
  layout: "app",
});

let editMode = false;

const { data: customer, pending } = await useAsyncData(async () => {
  const route = useRoute();
  const store = useCustomersStore();
  await store.fetchCustomer(route.params.id);
  return store.getCustomer;
});

async function updateCustomer(customer) {
  const route = useRoute();
  const store = useCustomersStore();
  await store.updateCustomer(route.params.id, customer);
  editMode = false;
}

async function setEditMode() {
  editMode = true;
}
</script>

<template>
  <div>
    <main>
      <div class="mx-auto max-w-7xl py-6 sm:px-6 lg:px-8">
        <AppCustomerDetail
          v-if="customer && !editMode"
          :customer="customer"
          class="max-w-4xl"
          @edit="setEditMode"
        />
        <AppCustomerForm
          v-if="customer && editMode"
          :customer="customer"
          class="max-w-4xl"
          @submit="updateCustomer"
        />
        <div v-if="!pending && !customer">Error</div>
      </div>
    </main>
  </div>
</template>

Data is fetched correctly.数据被正确获取。 The problem is that, even though I change the editMode value from false to true (and I printed to console the value correctly), the view does not change from CustomerDetail to CustomerForm.问题是,即使我将 editMode 值从 false 更改为 true(并且我打印以正确控制该值),视图也不会从 CustomerDetail 更改为 CustomerForm。 It seems that the variable is not reactive and is not re-evaluated.似乎变量不是反应性的,也没有重新评估。

Could you please point me to the right direction?你能给我指出正确的方向吗?

To declare a reactive variable you must declare your variable with the help of ref or reactive functions.要声明一个反应变量,您必须在refreactive函数的帮助下声明您的变量。

Do like this const editMode = ref(false)像这样const editMode = ref(false)

Later in the script setup to change the value of editMode editMode.value = true稍后在脚本设置中更改 editMode 的值editMode.value = true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM