VUE监听两个值的变化,同时执行一个方法,如何防止重复执行/和this.$nextTick()用法

展示

示例;
点击按钮改变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>

侦听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、使用computed计算属性定义一个返回值的方法。
2、监听该方法,即可
在这里插入图片描述

vue中this.nextTick()的用法

猜你喜欢

转载自blog.csdn.net/z18237613052/article/details/125285837