【问题标题】:How to avoid the duplicate codes in the different functions with Vue.js?Vue.js如何避免不同功能中的重复代码?
【发布时间】:2020-10-23 08:59:54
【问题描述】:

我既不习惯 Javascript 也不习惯 Vue.js。仍然通过做不同的事情来学习,我正在努力不使用Vue.js 在两个函数中使用重复的代码。我还没有想出如何解决这个问题。我有这个 button : <q-btn :style="{opacity: storeName.length==0 ? 0 : 1}" icon="close" @click="reset()"></q-btn> 以便输入值变为空并重置所有数据。这就是我的目标。

<template>
  <script>
    methods: {
      reset() {
        this.storeName = '';

        // These codes below are exactly the same with getStores() function..
        let params = {
          ap_dates: [
            this.date,
            moment(this.date).add(1, 'days').format('YYYY-MM-DD'),
          ],
          ap: ['orderCount', 'orderHasReceiptCount'],
        };

        if (this.storeName.length > 0) {
          params.f = ['name,%,' + this.storeName];
        }
        this.$http
          .get(`${this.$store.getters.apiPath}/store`, { params: params })
          .then((res) => {
            // console.log(res);
            this.stores = res.data.data;

            for (const key in this.total) {
              this.total[key] = 0;
              if (res.data.meta.totalOrderCount.hasOwnProperty(key)) {
                this.total[key] = res.data.meta.totalOrderCount[key];
              }
            }
            this.$forceUpdate();
          })
          .catch((err) => console.error(err))
          .finally(() => {
            this.loading = false;
            this.init = true;
          });
      },
      getStores() {
        this.loading = true;

        let params = {
          ap_dates: [
            this.date,
            moment(this.date).add(1, 'days').format('YYYY-MM-DD'),
          ],
          ap: ['orderCount', 'orderHasReceiptCount'],
        };

        if (this.storeName.length > 0) {
          params.f = ['name,%,' + this.storeName];
        }
        this.$http
          .get(`${this.$store.getters.apiPath}/store`, { params: params })
          .then((res) => {
            this.stores = res.data.data;

            for (const key in this.total) {
              this.total[key] = 0;
              if (res.data.meta.totalOrderCount.hasOwnProperty(key)) {
                this.total[key] = res.data.meta.totalOrderCount[key];
              }
            }

            this.$forceUpdate();
          })
          .catch((err) => console.error(err))
          .finally(() => {
            this.loading = false;
            this.init = true;
          });
      },
    }
  </script>
</template>

你能告诉我我应该怎么做吗?

【问题讨论】:

    标签: vue.js quasar-framework


    【解决方案1】:

    我想做的是这样的:

    reset() {
          this.storeName = '';
          this.getStores();
    },
    

    【讨论】:

      猜你喜欢
      • 2018-08-16
      • 1970-01-01
      • 2019-02-26
      • 2011-08-29
      • 1970-01-01
      • 2020-08-31
      • 2012-06-19
      • 1970-01-01
      相关资源
      最近更新 更多