nativescript-vue icon indicating copy to clipboard operation
nativescript-vue copied to clipboard

Watch of props not activated

Open vallemar opened this issue 3 years ago • 8 comments

When you declare a wath of a prop in a child component the event is not fired: Preview NS, Playground Vue3. You can see how the Details.vue watch is fired in vue but in NS-vue the event is never fired

vallemar avatar Jan 04 '23 07:01 vallemar

I can confirm that using defineComponent works instead. See, Preview NS. I'm not sure why the variant of SFC is not working 🤔

heywhy avatar Jan 22 '23 11:01 heywhy

Not destructuring the props actually works;

import { watch } from 'nativescript-vue';

const props = defineProps({
  text: String,
});

watch(
  () => props.text,
  () => {
    console.log("This watch should activate but it doesn't", props.text);
  }
);

heywhy avatar Jan 22 '23 12:01 heywhy

@heywhy I have noticed this in some components, I have some others that do not work like this either, I do not understand why in some it does and in others it does not

vallemar avatar Jan 22 '23 14:01 vallemar

In Vue 3 docs says:

Note that if you destructure the props object, the destructured variables will lose reactivity. It is therefore recommended to always access props in the form of props.xxx.

You can use toRefs if really need to destructure:

If you really need to destructure the props, or need to pass a prop into an external function while retaining reactivity, you can do so with the toRefs() and toRef() utility APIs:

const props = defineProps({
  text: String,
});

const { text } = toRefs(props)

watch(
  () =>text,
  () => {
    console.log("This watch should activate, text);
  }
);

igorjacauna avatar Apr 08 '23 00:04 igorjacauna

Hey @igorjacauna . I tried with you code. Bu it isn't works too. I would like you to give me an advice.

This is my code.

`

const props = defineProps({ tabs: { default: [], type: Array }, tabIndex: { default: 0, type: Number }, }); const { tabs, tabIndex } = toRefs(props);

watch( () => tabIndex, () => { console.log(tabIndex); } );

`

There isn't any output. But the tabIndex is changed of the p tag.

MykolaZhaivoroniuk avatar Sep 10 '23 15:09 MykolaZhaivoroniuk

I'm also facing this same issue. watch is not being called even though props are getting changed and the latest value is being displayed in the UI but not calling watch.

meghraj-suthar avatar May 17 '24 11:05 meghraj-suthar

@meghraj-suthar can you show your code?

It seems like the problem is decomposing the props, but it's not an NS-Vue problem, it seems to be vue's behavior. Check this comment https://github.com/nativescript-vue/nativescript-vue/issues/1024#issuecomment-1500739521

vallemar avatar May 18 '24 07:05 vallemar