JavaScript/Vue 中动态更改文本的更有效方法

More Efficient Method for Dynamically Changing Text in JavaScript/Vue

我在 Vue 中工作,我正在使用 setInterval()data() 属性.

动态更改文本

我有一个可行的方法,但我想知道是否有更多 efficient/way 来优化该方法...或者它是否已尽可能优化?

优化的意思:内存使用最好,代码是不是越简单越好?

 <h1>
    <span>{{ action }}</span> for everyone.
  </h1>
<script>
export default {
  name: "HeadLine",
  data() {
    return {
      action: "Build",
    };
  },
  methods: {
    changeTitle() {
     setInterval(() => {
        const actions = ["Build", "Create", "Design", "Code"];
        const currentActionIndex = actions.indexOf(this.action);
        //Send back to index of [0] === Build
        const nextActionIndex = (currentActionIndex + 1) % 4;
        let nextAction = actions[nextActionIndex];
        this.action = nextAction;
      }, 3000);
    },
  },
};
</script>

就渲染而言,Vue 已经做到了最好。

关于你的文本旋转功能,它可以改进一点,但它是一个简单的功能,你不会获得太多的内存使用。

// Stores the actions out of the component. It doesn't need to be reactive if it's static.
// You're avoiding having Vue's proxy above this array.
const actions = ["Build", "Create", "Design", "Code"];

export default {
  data () {
    return {
      // The only reactive data you need is the index of the word you want to show
      wordIndex: 0,
    }
  },
  computed: {
    // Let view update the text when the index changes. Computed properties use caching.
    action() {
      return actions[this.wordIndex]
    }
  },
  methods: {
    changeTitle() {
      setInterval(this.initRotation, 3000)
    },
    initRotation () {
      // Update the current word index
      this.wordIndex = (this.wordIndex + 1) % actions.length;
    }
  },
  beforeDestroy() {
    // Remove the interval runner when the component is destroyed!
    clearInterval(this.initRotation)
  }
}

如前所述,这不会显着改变组件性能。感觉改变已经太简单了