Home > Enterprise >  How to make Vue 3 props objects reactive?
How to make Vue 3 props objects reactive?

Time:01-13

This code is from a VueMastery course, which must be outdated:

export default {
  setup(props, {emit}){
    let email = props.email;
    let toggleRead = () => {
      email.read = !email.read
      axios.put(`http://localhost:3000/emails/${email.id}`, email)
    }
  ...

It gives this error:

   71:9   error  Getting a value from the `props` in root scope of `setup()` will cause the value to lose reactivity  vue/no-setup-props-destructure

Note that I am not dealing with const here. What is the correct way to make a prop value reactive in Vue 3?

CodePudding user response:

This warning is caused by linter rule that is supposed to improve code quality. If it's known that a prop isn't changed during the lifetime of component instance, it can be disabled.

The problem here is that the code mutates a prop, which is considered a bad practice and can trigger another warning.

For one-way change of prop value, i.e. a parent is unaware of it:

const toggleRead = () => {
  const email = { ...props.email, read: !email.read };
  axios.put(`http://localhost:3000/emails/${email.id}`, email)
}

For two-way change:

const toggleRead = () => {
  ...
  emit('emailUpdate', email);
}

A parent should listen to emailUpdate event and update its state accordingly.

  •  Tags:  
  • Related