【问题标题】:Vue JS - Loop through a computed property to display a list of yearsVue JS - 遍历计算属性以显示年份列表
【发布时间】:2021-10-08 13:44:03
【问题描述】:

我目前有以下列出年份列表的代码。我觉得所有这些代码可能都是非常不必要的,也许validYears 的计算属性会帮助我使这段代码更优化并摆脱不必要的观察者。我的问题是将其转换为计算属性,因为我没有掌握正确的逻辑来实现这一点。如果有人能提供一个示例,说明我如何为有效年份设置计算属性并仍然返回相同的结果,我将不胜感激。

    onBeforeMount(calculateDateRange)

    watch(() => props.earliestDate, (newValue, prevValue) => {
      calculateDateRange();
    });
    // If there is a new value passed from the parent, the dropdown should display that new value.
    watch(() => props.latestDate, (newValue, prevValue) => {
      calculateDateRange()
    });

    const validYears = ref([])
    function calculateDateRange () {
      for(let year = props.latestDate; year >= props.earliestDate; year--){
        validYears.value.push(year)
      }
    }

我没有提供其余代码以免使问题变得混乱,但正如在此组件中看到的那样,我有一组用于确定 for 循环中的值的道具。

【问题讨论】:

    标签: javascript vue.js vuejs3 vue-composition-api computed-properties


    【解决方案1】:

    您可以按如下方式对其进行优化:

    const validYears = computed(()=>{
        let _years=[]
        for(let year = props.latestDate; year >= props.earliestDate; year--){
            _years.push(year)
          }
     
      return _years;
    
    }) 
    

    【讨论】:

      猜你喜欢
      • 2017-06-30
      • 1970-01-01
      • 2014-01-23
      • 2019-09-22
      • 2017-03-12
      • 2020-09-19
      • 2019-10-25
      • 2020-04-03
      • 1970-01-01
      相关资源
      最近更新 更多