VUE listens to the change of two values and executes a method at the same time, how to prevent repeated execution / and usage of this.$nextTick()

exhibit

Example;
click the button to change two data in vuex

index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
    
    
  state: {
    
     orgno: "456",text: "汉字"},
  mutations: {
    
    
    setchang(state) {
    
     state.orgno = "123"  },
    settext(state) {
    
    state.text = "新的汉字"}
  },
  actions: {
    
     },
  modules: {
    
     }
})

home.vue

<template>
  <div class="main">
    <el-button @click="kai">给vuex传数据</el-button>
  </div>
</template>

<script>
import {
    
     mapState } from "vuex"; //方便使用state中数据
export default {
    
    
  data() {
    
    
    return {
    
    
      msg: [],
    };
  },
  computed: {
    
    
    ...mapState(["orgno", "text"]),
  },
  watch: {
    
    
    orgno: {
    
    
      handler(nal, old) {
    
    
        this.ges();
      },
    },
    text: {
    
    
      handler(nal, old) {
    
    
        this.ges();
      },
    },
  },
  methods: {
    
    
    ges() {
    
    
      for (var i = 0; i < 8; i++) {
    
    
        this.msg.push(i);
      }
    },
  },
};
</script>

The method of listening to vuex data is executed twice
insert image description here
Change

<template>
  <div class="main">
    <el-button @click="kai">给vuex传数据</el-button>
  </div>
</template>

<script>
import {
    
     mapState } from "vuex"; //方便使用state中数据
export default {
    
    
  data() {
    
    
    return {
    
    
      msg: [],
    };
  },
  computed: {
    
    
    ...mapState(["orgno", "text"]),
    change() {
    
    
      const {
    
     orgno, text } = this;
      return {
    
    
        orgno,
        text,
      };
    },
  },
  watch: {
    
    
    change: {
    
    
      handler(event) {
    
    
        if (event) {
    
    
          this.ges();
        }
      },
      deep: true,
    },
  },
  methods: {
    
    
    ges() {
    
    
      for (var i = 0; i < 8; i++) {
    
    
        this.msg.push(i);
      }
    },
  },
};
</script>

1. Use the computed property to define a method that returns a value.
2. Listen to this method, you can
insert image description here

The usage of this.nextTick() in vue

Guess you like

Origin blog.csdn.net/z18237613052/article/details/125285837