【问题标题】:Function to change the value after some time. Vuejs一段时间后更改值的功能。 Vuejs
【发布时间】:2020-06-14 09:22:41
【问题描述】:

我想在一段时间后更改布尔值并继续重复该过程。然后我想将值单独传递给子组件。这里的 changeActive() 是改变 active 布尔值的函数。我想将值更改为第一个道具,然后在一段时间后第二个道具等等。

<template>
<div style="width:300px; margin: auto;">
      <RatingLabel 
      :rating='rating[0]'
      :active='active'
      style="margin: auto;"
      />
      <RatingLabel 
      :rating='rating[1]'
      :active='active'
      style="float: right;"
      />
      <RatingLabel 
      :rating='rating[2]'
      :active='active'
      />
      <RatingLabel 
      :rating='rating[3]'
      :active='active'
      style="margin: auto;"
      />
</div>
</template>

<script>
import RatingLabel from '../atomic/RatingLabel'
import { mapState } from 'vuex'
export default {
      components: {
            RatingLabel,
      },

      data() {
            return {
                  active: false,
            }
      },

      methods: {
            changeActive() {
                  setTimeout(function(){ 
                        this.active = !this.active;
                        console.log(this.active)
                   }, 3000);
            }
      },

      mounted() {
            this.changeActive()
      },

      computed: mapState(['rating'])
}
</script>

【问题讨论】:

    标签: vue.js vue-props


    【解决方案1】:

    这是你需要做的:

    1. 不要重复该组件,而是添加一个v-for
    <RatingLabel v-for="(rating,i) in ratings" :key="i" :rating="rating"/>
    
    1. 由于每个 prop 都是独立的,所以需要将active 制作成一个列表,并根据索引将每个元素作为一个 prop 传递,如下所示:

    将此添加到data

    activeList: [],
    

    所以组件渲染将是:

    <RatingLabel v-for="(rating,i) in ratings" :key="i" :active="activeList[i] || false" :rating="rating"/>
    
    1. 由于每个时间段都需要将每个prop设置为true,所以需要setInterval函数:

    将此添加到data:

    time:''
    

    然后用它作为区间:

    mounted() {
        this.changeActive();
    },
    methods: {
         changeActive: function() {
              let count = 0;
              var x = setInterval(() => {      
                   this.activeList.push(true);
                   count++;
                   if (count == this.ratings.length) clearInterval(x);  
              }, 3000);        
         },
    },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多