我试图使用一个组件来改变编程语言的多年经验。为此,我使用几个按钮来加减年份,并使用“技术”道具来传递语言。即:PHP、JS等。
<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,我试图重用组件“years-exp”,因此每个变量都会更改每个全局变量。我按照本教程设法完成其中之一。然而,当我想用一个发射和监听事件重用years-exp组件时,它总是修改years_php变量,所以我不得不使用'test'prop并检查它在不同情况下的值,这是我的years-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']
});
并将以下代码添加到我的 Vue 实例中:
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>
在 Vue.JS 2+ 中是否有另一种方法可以做到这一点?