子组件未在 Vue 3 中更新

时间:2021-03-07 19:42:50

标签: typescript vuejs3 vue-reactivity

我有一个 Vue3 应用程序,我想验证一个步骤。如您所见,pageControl 是应该接收道具的子组件。

问题是子组件首先获取道具,但是当我更新父组件内的值(道具)时(以const firstName = computed(开头的行),子组件不会触发或更新。

有什么想法会很感激吗?

这是我的父组件:

<template>
     <input type="text" v-model="firstName" />
    {{ nextStep.isDisabled }} //**** here the value will change *****//
    <pageControl :previous-step="previousStep" :next-step="nextStep" />
</template>

<script lang="ts">
import { defineComponent, inject, computed } from "vue";
import { useRouter } from "vue-router";
import pageControl from "@/components/pageControl.vue";

interface State {
  firstName: string;
  lastName: string;
  githubUsername: string;
  email: string;
  hasAcceptedTermsAndServices: boolean;
}
interface Store {
  state: State;
  methods: () => void;
  getters: () => void;
}

export default defineComponent({
  name: "RequestForm",
  components: {
    pageControl
  },
  setup() {
    const store: State | undefined = inject("store");
    const router = useRouter();

    const nextStep = {
      action: () => {
        router.push("/github-info");
      },
      isDisabled: true,
    };
    const previousStep = {
      action: () => {
        router.push("/");
      },
      isDisabled: false,
    };
    const firstName = computed({
      get() {
        return (store as any).state.firstName;
      },
      set(val) {
        (store as any).methods.updateFirstName(val);
        nextStep.isDisabled = !(store as any).getters.isValidPersonalInfo();
      }
    });
    return {
      store,
      nextStep,
      previousStep,
      firstName
    };
  }
});
</script>

子组件:

<template>
  <nav class="page-control__container">
    <button
      v-if="nextStep"
      :disabled="nextStep.isDisabled"
      @click="nextStep.action"
    >
      {{ nextStep.label }}
    </button>
  </nav>
</template>

<script>
import pageValidator from "@/utils/pageValidator";

export default {
  name: "pageControl",
  props: {
    nextStep: {
      type: Object,
      required: false,
      default: null,
      validator: pageValidator
    },
  }
};
</script>

1 个答案:

答案 0 :(得分:2)

为了让 vue 理解变化的反应性数据,您需要在 reactive() 方法中定义您的值。

    import { reactive } from "vue";
    const nextStep = reactive({
      action: () => {
        router.push("/github-user");
      },
      isDisabled: true,
    });