2017-02-01 2 views
0

VueJs에서 약간 분실했습니다. 구성 요소와 Vue로 업데이트 된 데이터로 vue를 만들려고합니다.부모로부터 vuejs 구성 요소를 업데이트하는 방법

부모 값을 $ emit으로 업데이트하는 방법을 이해했습니다.

수있는 사람의 전화이

<div id="app2" v-cloak> 
    <p>{{labels.lbl1}}: {{values.value}}</p> 
    how direct set {{labels.lbl1}} here: <input type="text" v-model:value="values.value"> can set the child value? 
    <hr/> 
    <child2 v-model:value="values.value" v-bind:lbl="labels.lbl1"></child2> 
</div> 

<template id="child2"> 
    <div> 
    Set {{internallbl1}} in child: 
    <input type="text" v-model="internalValue" > 
    <p>Value : {{value}}</p> 
    </div> 
</template> 

JS 코드

html로 코드 가능한 경우 : 여기

Vue.component('child2', { 
    template: '#child2', 

    //The child has a prop named 'value'. v-model will automatically bind to this prop 
    props: ['value','lbl'], 
    data: function() { 
    return { 
     internalValue: '', 
     internallbl1:'' 
    } 
    }, 
    watch: { 
    'internalValue': function() { 
     // When the internal value changes, we $emit an event. Because this event is 
     // named 'input', v-model will automatically update the parent value 
     this.$emit('input', this.internalValue); 
    } 
    }, 
    created: function() { 
    // We initially sync the internalValue with the value passed in by the parent 
    this.internalValue = this.value; 
    this.internallbl1 = this.lbl; 
    } 
}); 
new Vue({ 
    el: '#app2', 
    data: { 
    labels : {lbl1:'Parent value 1'}, 
    values : {value: 'hello'}, 
    } 
}); 

가 jsFiddle입니다 :

https://jsfiddle.net/davidhequet/ag0thqar/5/ 감사합니다, 데이비드

답변

1

부모님의 값이 바뀌면 internalValue은 바뀌지 않습니다. 당신은 value에 감시자를 설정하고이 변경 될 때마다, 다음과 같이, internalValue을 설정할 수 있습니다

Vue.component('child2', { 
    template: '#child2', 
    ... 
    ... 
    ... 
    created: function() { 
    // We initially sync the internalValue with the value passed in by the parent 
    this.internalValue = this.value; 
    this.internallbl1 = this.lbl; 
    }, 
    watch: { 
    'internalValue': function() { 
     // When the internal value changes, we $emit an event. Because this event is 
     // named 'input', v-model will automatically update the parent value 
     this.$emit('input', this.internalValue); 
    },  
    value: function(newVal) { 
     this.internalValue = newVal 
    } 
    }, 
}); 

fiddle 작업을 참조하십시오.

관련 문제