快应用如何基于 watch computed 监听多个变量?

快应用 Jun 17, 2022

在快应用开发中,如何监听多个变脸呢?与 Vue 一样,快应用中的 watch 监听,单纯的使用 watch 无法监听多个变量;如果某些操作,需要多个参数都更新后,才能执行,在自组件中如何能知道这个时机呢?变通方法之一,可通过 computed 计算属性返回一个对象,然后使用 watch 监听这个计算属性,只要值改变就会触发 watch,如此即能达成目的。

子组件示例写法

<template>
  <div class="wrapper">
    <text class="title">firstName: {{ firstName }}</text>
    <text class="title">lastName: {{ lastName }}</text>
  </div>
</template>

<script>
export default {
  data: {
    title: "Hello World. Quickapp Component."
  },

  computed: {
    fullName() {
      return {
        firstName: this.firstName,
        lastName: this.lastName
      }
    }
  },

  props: {
    firstName: {
      default: 'Hello' //默认值
    },
    lastName: {
      default: 'World' //默认值
    },
  },

  onInit() {
    this.$watch('fullName', 'watchPropsChange')
  },

  watchPropsChange(newVal, oldVal) {
    console.info(`Okay 👌, Perfect 监听到多个数据变化`, newVal, oldVal)
    if (newVal.firstName && newVal.lastName) {
      console.log(`Congratulations 🎉, 监听的两个数据,均已发生变化,可以执行更多操作了。`)
    }
  }
}
</script>

<style>
.wrapper {
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.title {
  text-align: center;
  color: #212121;
}
</style>

父组件调用示例

<template>
  <div class="wrapper">
    <watch-multi-val first-name="{{firstName}}" last-name="{{lastName}}"></watch-multi-val>
  </div>
</template>

<import name="watch-multi-val" src="./../../components/watch-multi-val.ux"></import>
 
<script>
export default {
  private: {
    firstName: "",
    lastName: ""
  },

  onInit() {
    setTimeout(() => {
      this.firstName = "Arya"
    }, 0)

    setTimeout(() => {
      this.lastName = "Stark"
    }, 1000)
  }
}
</script>

Vue 中如何监听多个属性

事实上,Vue2 官方也没有提供相关方法,来监听多个属性,也需要借助 computed,或者 watch 多个属性,调用同一处理函数。但在 Vue3,官方给出了更为便捷的解决方案,代码示例如下:

import { watch, ref } from 'vue';

export default {
  setup(() => {
    const a = ref(1), b = ref('hello');

    watch([a, b], ([newA, newB], [prevA, prevB]) => {
      // do whatever you want
    });
  });
};

猜您可能感兴趣的文章

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.