2016-11-14 39 views
0

我试图使用一个组件,它改变了编程语言的多年经验。为了做到这一点,我使用了几个按钮来增加和减少这些年份,并使用'tech'来传递语言。即: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,以及即时通讯试图重用组件“年-EXP”,所以每一个改变每个全局变量。我设法按照this教程做其中的一个。但是,当我想重复使用只有一个发射和侦听事件的年份exp组件时,它总是修改了年份_php变量,所以我必须使用'test'prop并检查它的值以适应不同的情况,这里是我的年份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> 

有另一种方式为V做到这一点ue.JS 2+?

回答

0

VueJS 2使用事件模式来处理父子通信。 所以基本上,为了让孩子和家长沟通,你不一定需要bus。你可以做到以下几点:

//your re-usable component code 
this.$emit('years-changed', years); 


//your component that uses <years-exp> (parent of years-exp) 
<years-exp test="years_php" tech="PHP" @years-changed="handleYearsChanged"></years-exp> 

methods:{ 
    handleYearsChanged:function(yearsValueFromChild){ 
    //here you receive exactly the value you sent via $emit in child 
    } 
} 

如果你需要将事件发送到层次中的父以上的成分,那么你将不得不使用bus但对于亲子沟通,你可以使用这个非常简单的模式。

+0

谢谢你的回答!在handleYearsChanged()里面,我将如何区分与years_php绑定的年份以及与years_js绑定的年份,如果我只有一个发出事件为他们两个?或者你建议每个组件有不同的方法,例如:handlePHPYearsChanged(),handleJSYearsChanged()等 –

+0

@AlexanderOyarzabal是的,你不要在孩子中区分它们,只是将不同的处理程序绑定到父代中的'years-changed' ,正如你所说的那样。 –