Subscribe on changes!

props default value inconsistent behavior with vue 2

avatar
Apr 11th 2022

Version

3.2.31

Reproduction link

stackblitz.com

Steps to reproduce

Vue 3: https://stackblitz.com/edit/vue-erg87v?file=src%2FApp.vue

Vue 2: https://stackblitz.com/edit/vue2-vue-cli-mjakzv?file=src%2FApp.vue

In Vue 3:

  1. input obj.name, type 123 (obj.name: [] doesn't update )
  2. click first input, type anything to trigger child component update (obj.name update to obj.name: [123])
  3. input str1, error: proxy set handler returned false for property '"str1"'

In Vue 2:

  1. input obj.name, type 123 (obj.name: [] update to obj.name: [123])
  2. click first input, type anything to trigger child component update (obj.name: [123] doesn't update)
  3. input str1, warning: [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "str1"

What is expected?

Vue 2 behavior is more reasonable

What is actually happening?

above

avatar
Apr 11th 2022

A workaround (wrap prop default value with reactive, ref doen't work):

import { ref, reactive } from 'vue';
export default {
  props: {
    obj: {
      type: Object,
      default() {
        return reactive({ name: '' });
      },
    },
  },
};

https://stackblitz.com/edit/vue-wjiyzs?file=src%2Fcomponents%2FHelloWorld.vue

avatar
Apr 11th 2022

The warning could be better but you are not supposed to modify a prop so the behavior is expected

avatar
Apr 12th 2022