首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >设置Getters和Setters

设置Getters和Setters
EN

Stack Overflow用户
提问于 2021-04-24 18:00:25
回答 1查看 339关注 0票数 0

应将TableFields.vue中的变量startStopA...InitialValueA...移动到存储index.js。当您将其移动到存储时,会出现错误“没有设置setters ...”。我已经阅读了一份文档,并尝试了我能想到的所有方法,但没有设法将其设置正确。

TableFields.vue组件

代码语言:javascript
复制
<template>
  <div>
    <div class="wrapper" v-for="(field, index) in fields" :key="index">
      <table>
        <tr>
          <th>{{ field }}</th>
          <td class="sign">{{ randomSign[index] }}</td>
          <td class="value">{{ initialValues[index].toFixed(2) }}</td>
          <td v-show="$store.state.randomSign[index] === '+'">&#x2B06;</td>
          <td v-show="$store.state.randomSign[index] === '-'">&#x2B07;</td>
        </tr>
      </table>

      <button
        @click="toggleInterval(field)"
        v-if="field === 'A'"
        :class="[startStopA ? 'button-start' : 'button-stop']"
      >
        <span v-show="startStopA">Stop</span>
        <span v-show="!startStopA">Start</span>
      </button>

      <button
        @click="toggleInterval(field)"
        v-if="field === 'B'"
        :class="[startStopB ? 'button-start' : 'button-stop']"
      >
        <span v-show="startStopB">Stop</span>
        <span v-show="!startStopB">Start</span>
      </button>

      <button
        @click="toggleInterval(field)"
        v-if="field === 'C'"
        :class="[startStopC ? 'button-start' : 'button-stop']"
      >
        <span v-show="startStopC">Stop</span>
        <span v-show="!startStopC">Start</span>
      </button>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex';

export default {
  name: 'TableFields',
  data () {
    return {
      startStopA: true,
      startStopB: true,
      startStopC: true,
      initialValueA: 3,
      initialValueB: 3,
      initialValueC: 3,
      arraysInterval: null
    };
  },
  computed: {
    ...mapState([
      'changes',
      'timer',
      'fields',
      'signs',
      'randomSign',
      'randomNumbers'
    ]),

    initialValues () {
      let array;
      array = [
        this.initialValueA,
        this.initialValueB,
        this.initialValueC
      ];
      return array;
    }
  },
  methods: {
    ...mapMutations(['replaceNumbersArray']),

    toggleInterval (field) {
      // button toggle
      if (field === 'A') {
        this.startStopA = !this.startStopA;
        if (this.startStopA) {
          this.timer[0] = setInterval(() => {
            this.calculations('A');
          }, 2000);
        } else {
          clearInterval(this.timer[0]);
        }
      }
      if (field === 'B') {
        this.startStopB = !this.startStopB;
        if (this.startStopB) {
          this.timer[1] = setInterval(() => {
            this.calculations('B');
          }, 2000);
        } else {
          clearInterval(this.timer[1]);
        }
      }
      if (field === 'C') {
        this.startStopC = !this.startStopC;
        if (this.startStopC) {
          this.timer[2] = setInterval(() => {
            this.calculations('C');
          }, 2000);
        } else {
          clearInterval(this.timer[2]);
        }
      }
      if (!this.startStopA && !this.startStopB && !this.startStopC) {
        clearInterval(this.arraysInterval);
      }
    },
    calculations (field) {
      this.fields.forEach((value, index) => {
        if (field === value) {
          this.randomSign[index] = this.signs[
            Math.floor(Math.random() * this.signs.length)
          ];
          const date = new Date();
          const newChange = [];

          newChange.field = field;
          newChange.indicator = this.randomSign[index];
          newChange.value = this.randomNumbers[index];
          newChange.time = date.toLocaleTimeString();

          this.changes[index].push(newChange);
        }
      });

      if (field === 'A') {
        this.randomSign[0] === '+'
          ? (this.initialValueA += this.randomNumbers[0])
          : (this.initialValueA -= this.randomNumbers[0]);
      }

      if (field === 'B') {
        this.randomSign[1] === '+'
          ? (this.initialValueB += this.randomNumbers[1])
          : (this.initialValueB -= this.randomNumbers[1]);
      }

      if (field === 'C') {
        this.randomSign[2] === '+'
          ? (this.initialValueC += this.randomNumbers[2])
          : (this.initialValueC -= this.randomNumbers[2]);
      }
    }
  },
  beforeUpdate () {
    const array = [this.startStopA, this.startStopB, this.startStopC];
    array.forEach((value, index) => {
      if (!value) {
        clearInterval(this.timer[index]);
      }
    });
  },
  mounted () {
    console.log(`${this.changes}`);
    this.arraysInterval = setInterval(this.replaceNumbersArray, 2000);

    this.fields.forEach((value, index) => {
      this.timer[index] = setInterval(() => {
        this.calculations(value);
      }, 2000);
    });

    this.initialValueA = this.$root.initialValueA || 3;
    this.initialValueB = this.$root.initialValueB || 3;
    this.initialValueC = this.$root.initialValueC || 3;

    this.startStopA = !this.$root.startStopA || !this.startStopA;
    this.startStopB = !this.$root.startStopB || !this.startStopB;
    this.startStopC = !this.$root.startStopC || !this.startStopC;

  },
  beforeDestroy () {
    clearInterval(this.arraysInterval);

    this.$root.initialValueA = this.initialValueA;
    this.$root.initialValueB = this.initialValueB;
    this.$root.initialValueC = this.initialValueC;

    this.$root.startStopA = !this.startStopA;
    this.$root.startStopB = !this.startStopB;
    this.$root.startStopC = !this.startStopC;

    this.timer.forEach(value => {
      clearInterval(value);
    });
  }
};
</script>

store/index.js文件:

代码语言:javascript
复制
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    changes: [],
    timer: [0, 0, 0],
    fields: ['A', 'B', 'C'],
    signs: ['+', '-'],
    randomSign: ['+', '+', '+'],
    randomNumbers: []
  },
  mutations: {
    replaceNumbersArray (state) {
      // replace random A, B, C... numbers at time interval
      const A = Number((Math.random() + 1).toFixed(2)); // first number A
      const B = Number((Math.random() + 1).toFixed(2)); // first number B
      const C = Number((Math.random() + 1).toFixed(2)); // first number C
      state.randomNumbers.splice(0, 3, A, B, C);
      console.log(state.randomNumbers);
    }
  }
});

export default store;

GitHub存储库:

https://github.com/SrdjanMilic/Super-Dynamic-Data

Codesandbox:

https://codesandbox.io/s/super-dynamic-data-djpxe

EN

回答 1

Stack Overflow用户

发布于 2021-04-24 18:44:16

您需要为每个要更改的计算属性实现一个setter,因为在Vuejs中,默认情况下,计算属性是唯一的getter:

VueJS文档:

默认情况下,

计算属性是仅限getter的,但您也可以在需要时提供setter

这样编写的计算属性将如下所示(同样,来自VueJS文档):

代码语言:javascript
复制
fullName: {
    // getter
    get: function () {
      return this.firstName + ' ' + this.lastName
    },
    // setter
    set: function (newValue) {
      var names = newValue.split(' ')
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }

也就是说,我的建议是,如果想让你的突变在整个代码库中可重用,那么可以用另一种方法来实现,将突变实现为存储操作/突变,并从组件方法(或使用mapActions...etc)触发它们。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67241499

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档