프로그래밍 언어로 수년 간의 경험을 변경하는 구성 요소를 사용하려고합니다. ir 명령을 사용하려면 몇 개의 버튼을 사용하여 년을 더하거나 뺍니다. 그리고 언어를 전달하는 '기술'소품을 사용합니다. 즉 : PHP, JS 등vue.js 2 두 개의 다른 부모 변수로 구성 요소 다시 사용
<script type="text/template" id="years_template">
<div>
<p>How mane years of experience with {{ tech }} do you have?</p>
<p>
Answer: <strong>{{ years }}</strong>
<button type="button"
class="btn"
@click="add">+</button>
<button type="button"
:disabled="years == 0"
class="btn"
@click="sub">-</button>
</p>
</div>
</script>
내 전역 변수가 years_php 및 years_JS, 그리고 메신저 구성 요소 "년 - 특급"을 재사용하려고 그렇게 하나 하나는 각각의 전역 변수를 변경합니다. 나는 this 자습서를 따라 그들 중 하나를 할 수있다. 그러나 years-exp 컴포넌트를 하나의 방출 및 청취 이벤트로 재사용하고 싶을 때, 항상 years_php 변수를 수정 했으므로 '테스트'소품을 사용하고 다른 케이스에 대한 값을 확인해야했습니다. 여기에 내 년 EXP가 있습니다. 구성 요소 :
Vue.component('years-exp', {
template: '#years_template',
data(){
return {
years : 0
}
},
watch:{
'years': function(years, oldYears){
console.log('years changed from %s to %s', oldYears, years)
switch (this.test) {
case "years_php":
bus.$emit('PHPyears-changed', years);
break;
case "years_js":
bus.$emit('JSyears-changed', years);
break;
}
},
},
methods: {
add: function() {
this.years++;
},
sub: function() {
this.years--;
},
},
props: ['test','tech']
});
그리고 내 뷰 인스턴스에 다음 코드를 추가
created: function() {
// store this to use with Vue.set
var temp = this;
bus.$on('PHPyears-changed', function (years) {
Vue.set(temp, 'years_php', years);
//Vue.set(temp, 'years_js', years)
});
bus.$on('JSyears-changed', function (years) {
Vue.set(temp, 'years_js', years);
//Vue.set(temp, 'years_js', years)
})
},
그리고 여기에 내가 HTML에 삽입 :
<years-exp test="years_php" tech="PHP"></years-exp>
<years-exp test="years_js" tech="JS"></years-exp>
V에서이 작업을 수행하는 또 다른 방법이 있나요 ue.JS 2+?
답장을 보내 주셔서 감사합니다. handleYearsChanged() 내에서 years_php와 바인딩 된 연도와 years_js와 연결된 연도를 구분하는 방법은 무엇입니까? 아니면 각 구성 요소마다 다른 방법을 제안하십시오 : handlePHPYearsChanged(), handleJSYearsChanged(), etc. –
@AlexanderOyarzabal 예, 당신은 자식에서 그들을 차별화하지 않고 단지 다른 처리기를 부모에서'years-changed'에 바인딩합니다 , 당신이 진술 한대로. –