3
votes

I am using the Vue composition API in one of my components and am having some trouble getting a component to show the correct rendered value from a computed prop change. It seems that if I feed the prop directly into the components render it reacts as it should but when I pass it through a computed property it does not.

I am not sure why this is as I would have expected it to be reactive in the computed property too?

Here is my code:

App.vue

<template>
  <div id="app">
    <Tester :testNumber="testNumber" />
  </div>
</template>

<script>
import Tester from "./components/Tester";

export default {
  name: "App",
  components: {
    Tester,
  },
  data() {
    return {
      testNumber: 1,
    };
  },
  mounted() {
    setTimeout(() => {
      this.testNumber = 2;
    }, 2000);
  },
};
</script>

Tester.vue

<template>
  <div>
    <p>Here is the number straight from the props: {{ testNumber }}</p>
    <p>
      Here is the number when it goes through computed (does not update):
      {{ testNumberComputed }}
    </p>
  </div>
</template>

<script>
import { computed } from "@vue/composition-api";

export default {
  props: {
    testNumber: {
      type: Number,
      required: true,
    },
  },
  setup({ testNumber }) {
    return {
      testNumberComputed: computed(() => {
        return testNumber;
      }),
    };
  },
};
</script>

Here is a working codesandbox:

https://codesandbox.io/s/vue-composition-api-example-forked-l4xpo?file=/src/components/Tester.vue

I know I could use a watcher but I would like to avoid that if I can as it's cleaner the current way I have it

1

1 Answers

4
votes

Don't destruct the prop in order to keep its reactivity setup({ testNumber }) :

setup(props) {
return {
  testNumberComputed: computed(() => {
    return props.testNumber;
  }),
};
}