What's the correct way to pass props as initial data in Vue.js 2?

后端 未结 3 1788
無奈伤痛
無奈伤痛 2020-12-12 11:00

So I want to pass props to an Vue component, but I expect these props to change in future from inside that component e.g. when I update that Vue component from inside using

3条回答
  •  被撕碎了的回忆
    2020-12-12 11:46

    In companion to @dominik-serafin's answer:

    In case you are passing an object, you can easily clone it using spread operator(ES6 Syntax):

     props: {
       record: {
         type: Object,
         required: true
       }
     },
    
    data () { // opt. 1
      return {
        recordLocal: {...this.record}
      }
    },
    
    computed: { // opt. 2
      recordLocal () {
        return {...this.record}
      }
    },
    

    But the most important is to remember to use opt. 2 in case you are passing a computed value, or more than that an asynchronous value. Otherwise the local value will not update.

    Demo:

    Vue.component('card', { 
      template: '#app2',
      props: {
        test1: null,
        test2: null
      },
      data () { // opt. 1
        return {
          test1AsData: {...this.test1}
        }
      },
      computed: { // opt. 2
        test2AsComputed () {
          return {...this.test2}
        }
      }
    })
    
    new Vue({
      el: "#app1",
      data () {
        return {
          test1: {1: 'will not update'},
          test2: {2: 'will update after 1 second'}
        }
      },
      mounted () {
        setTimeout(() => {
          this.test1 = {1: 'updated!'}
          this.test2 = {2: 'updated!'}
        }, 1000)
      }
    })
    
    
    

    https://jsfiddle.net/nomikos3/eywraw8t/281070/

提交回复
热议问题