0

我试图使用一个组件来改变编程语言的多年经验。为此,我使用几个按钮来加减年份,并使用“技术”道具来传递语言。即: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+ 中是否有另一种方法可以做到这一点?

4

1 回答 1

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但是对于父子通信,您可以使用这个非常简单的模式。

于 2016-11-14T09:49:20.170 回答