vue.jstwo-way

vuejs: object type of computed value can't support two-way data binding


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/


Solution

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

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

    local: this.serviceData