Home > Mobile >  Vue 3 doesn't update component UI on props change
Vue 3 doesn't update component UI on props change

Time:09-06

I want my child component to be updated once props were changed. But it doesn't happens:

    // App.vue
    <template>
      <div id="app">
        <Foo :foo="foo" />
      </div>
    </template>
    
    <script setup>
      import Foo from '@/components/Foo.vue'
    
      const foo = { a: 1, b: 2 }
    
      //Updating the value of the passed constant each 0.5 seconds
      setInterval(() => {
        foo.a  = 1
        foo.b  = 1
      }, 500)
    </script>

Child component:

    // Foo.vue
    <template>
      <div>
        <div>Value A: {{ foo.a }}</div>
        <div>Value B: {{ foo.b }}</div>
      </div>
    </template>
    
    <script setup>
      const props = defineProps({ foo: { a: 0, b: 0 } })
    </script>

If I put console.log in Foo.vue I can see the value is changing, but can't see those changes in the ui.

I have a guess: Not sure, but maybe instead of const foo = { a: 1, b: 2 } should be const foo = reactive({ a: 1, b: 2 })? Seems to be working. But I wonder – is this a best practice? Because in the previous Vue that wasn't needed. And anyway would be nice to sure that changes are tracked on the Foo.vue side, instead of checking all the usages of that component.


P.S. I'm pretty sure that this question was asked before, but it's hard to find an answer due to overlapping with the previous version of vue.

CodePudding user response:

You must use ref or reactive if you want variables to be reactive

Check out this link to find out more.

In your case, here's how to do it

      import {ref} from 'vue'
      import Foo from './Foo.vue'
    
      const foo = ref({ a: 1, b: 2 })
    
      //Updating the value of the passed constant each 0.5 seconds
      setInterval(() => {
        foo.value.a  = 1
        foo.value.b  = 1
      }, 500)

Playground example

  • Related