侦听属性 watch

示例

  1. <template>
  2. <view>
  3. <text>fullName is : "{{ fullName }}"</text>
  4. </view>
  5. </template>
  6. <script>
  7. class Index {
  8. data = {
  9. firstName: 'Foo',
  10. lastName: 'Bar',
  11. fullName: 'Foo Bar'
  12. }
  13. watch = {
  14. firstName: function (newV, oldV) {
  15. this.fullName = newV + ' ' + this.lastName
  16. },
  17. lastName: function (newV, oldV) {
  18. this.fullName = this.firstName + ' ' + newV
  19. }
  20. }
  21. };
  22. export default new Index();
  23. </script>

除了 watch 选项之外,你还可以使用命令式的 this.$watch API。

但是,上面代码是命令式且重复的。将它与计算属性的版本进行比较:

  1. <script>
  2. class Index {
  3. data = {
  4. firstName: 'Foo',
  5. lastName: 'Bar'
  6. }
  7. computed = {
  8. fullName: function () {
  9. return this.firstName + ' ' + this.lastName
  10. }
  11. }
  12. }
  13. </script>

所以,不要滥用 watch ~