0

In my Vuejs(2.x version), I came across as following:

Vue.component('service',{
    template: '<div>' +
              '<div>{{serviceData.serviceName}}</div>' +  
              '<input v-model="serviceData.serviceName">' +
              '</div>',
    props: ['serviceData'],
})

var demo = new Vue({
    el: '#demo',
    data: {
        allData: {
            serviceName: 'Service1',
            serviceType: '0',
            otherInfo: 'xxxinfo',
        },
    },
    computed: {
        serviceData() {
            return {
                serviceName: this.allData.serviceName,
                serviceType: this.allData.serviceType,
           };
        },
    },
 })

 <div id="demo">
    <service :service-data="serviceData"></service>
 </div>

as above, in my Vue instance I have the original data of alldata, which is an object type. And since it contains some other non-related information. I created an object by computed which only contains related information and name it as serviceData.

And pass the serviceData object to the component service via props.
In the service component, I have an input element which two way bind to serviceData.serviceName with v-model.

But it turns out the two way binding can't work correctly.

So how to add reactivity in this case.

Please refer to this live demo:

https://jsfiddle.net/baoqger/t3mr9de3/1/

Chris Bao
  • 2,418
  • 8
  • 35
  • 62
  • I think that encompasing vuex to your application would be best approach. –  Jul 31 '17 at 12:55

2 Answers2

1

I'm not sure if you can use a nested computed object. But you can use the following in general.

  computed: {
    serviceName: {
      get: function() {
        return this.allData.serviceName
      },
      set: function(newVal) {
        this.allData.serviceName = newVal;
      }
    }
  }

Doing so you obviously have to adjust the passed in props. Also, if you use this method, Vue will warn you about mutating passed in props.

A better way or basically the correct way would be to $emit an event in your child component through custom events and update the data in your parent component accordingly.

tony19
  • 125,647
  • 18
  • 229
  • 307
Aer0
  • 3,792
  • 17
  • 33
0

the answer is here:https://jsfiddle.net/66ffqtej/

you can localize the date in the component ,can it can work.

local: this.serviceData
ThatToti
  • 24
  • 4