VUEが2つの値の変化をリッスンしてメソッドを同時に実行する、繰り返し実行を防ぐ方法とthis.$nextTick()の使い方

展示する

例:
vuex で 2 つのデータを変更するにはボタンをクリックします

インデックス.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>

vuex データをリッスンするメソッドが 2 回実行されました
ここに画像の説明を挿入
変更

<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. 計算プロパティを使用して、値を返すメソッドを定義します。
2. このメソッドを聞いて、次のことができます。
ここに画像の説明を挿入

vue での this.nextTick() の使用法

おすすめ

転載: blog.csdn.net/z18237613052/article/details/125285837