setTimeout方法,(交换组件)

时间:2017-10-05 20:20:20

标签: javascript vue.js vue-component

所以我试图创建一个setTimeout方法。所以当有人按下三个按钮中的一个时(滴水,法式压力机,Aeropress)。 setTimeout方法的.5秒将触发事件。将{{ShowText}}换成{{ShowText2}}哪个等待' + this.order_type

Accept: application/json

______________ JS _______________________________

  <div id="app">
    <barista-template></barista-template>
</div>

<!--template for customer-->
<script type="text/x-template" id="b-template">
    <div>
        <div>{{showText}}</div>
        <button v-on:click="choose('drip')">Drip</button>
        <button v-on:click="choose('frenchpress')">French Press</button>
        <button v-on:click="choose('aeropress')">Aeropress</button>
        <div>{{showText2}}</div>
    </div>
</script>

<script type="text/x-template" id="c-template">
    <div>
        <div>{{showText2}}</div>
    </div>
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.4/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.1/TweenMax.min.js"></script>
<script src="JS/app.js"></script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

这是你正在寻找的那种行为吗?我添加了一个swapping变量来指示何时进行交换(意味着显示showText2)。

swapComponentswapping设置为true,然后使用setTimeout将其设置回falsechoose致电swapComponent

Vue.component("barista-template", {
  template: "#b-template",
  data: function() {
    return {
      order_type: "",
      order_value: "",
      swapping: false
    }
  },
  computed: {
    showText() {
      if (this.order_type === '') return '';
      return 'One ' + this.order_type + ' that would be ' + this.order_value
    },
    showText2() {
      if (this.order_type === '') return '';
      return 'waiting for ' + this.order_type
    }
  },
  methods: {
    swapComponent: function() {
      this.swapping = true;
      setTimeout(() => {
        this.swapping = false;
      }, 1500);
    },
    choose: function(order_type) {
      this.swapComponent();
      this.order_type = order_type;

      if (this.order_type == "drip") {
        this.order_value = "$10";
      }
      if (this.order_type == "frenchpress") {
        this.order_value = "$20";
      }
      if (this.order_type == "aeropress") {
        this.order_value = "$30";
      }
    }
  }
});
new Vue({
  el: "#app",
  data: function() {
    return {
      showing: true
    }
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
  <barista-template></barista-template>
</div>

<!--template for customer-->
<script type="text/x-template" id="b-template">
  <div>
    <div>{{swapping ? showText2 : showText}}</div>
    <button v-on:click="choose('drip')">Drip</button>
    <button v-on:click="choose('frenchpress')">French Press</button>
    <button v-on:click="choose('aeropress')">Aeropress</button>
  </div>
</script>