Page & Component 新增的实例方法

this.$watch

用于动态添加watch,返回值是一个destroy函数,执行返回函数用于销毁watch

参数选项
  • this.$watch(expr | function, callback, options?: Object) : function
  1. import {createComponent} from '@mpxjs/core'
  2. createComponent({
  3. data: {
  4. info: {
  5. name: 1
  6. }
  7. },
  8. attached () {
  9. // 微信小程序生命周期
  10. // 第一个参数为变量表达式
  11. const unwatch1 = this.$watch('info.name', (val, old) => {
  12. console.log(val, old)
  13. }, {
  14. // deep: true,
  15. // sync: true,
  16. immediate: true // watch options
  17. })
  18. unwatch1() // 销毁watch,不再观察
  19. // 第一个参数也可以为函数
  20. this.$watch(function() {
  21. return this.info.name
  22. }, (val, old) => {
  23. console.log(val, old)
  24. }, {
  25. // deep: true,
  26. // sync: true,
  27. immediate: true // watch options
  28. })
  29. }
  30. })

$nextTick

接收一个函数,保证在小程序渲染更新之后执行回调

  1. import {createComponent} from '@mpxjs/core'
  2. createComponent({
  3. data: {
  4. info: {
  5. name: 1
  6. }
  7. },
  8. attached () {
  9. this.info.name = 2
  10. this.$nextTick(() => {
  11. console.log('会在由name变化引起的视图更新之后执行')
  12. })
  13. }
  14. })

$updated

已被废弃,请使用this.$nextTick代替

$forceUpdate

参数选项
  • this.$forceUpdate(data?: Object, callback?: function)

用于强制刷新视图,正常情况下只有发生了变化的数据才会被发送到视图层进行渲染。强制更新时,会将某些数据强制发送到视图层渲染,无论是否发生了变化

  1. import {createComponent} from '@mpxjs/core'
  2. createComponent({
  3. data: {
  4. info: {
  5. name: 'a'
  6. },
  7. age: 100
  8. },
  9. attached () {
  10. // 虽然不会修改age的值,但仍会触发重新渲染,并且会将age发送到视图层
  11. this.$forceUpdate({
  12. age: 100
  13. }, () => {
  14. console.log('视图更新后执行')
  15. })
  16. // 也可用于正常的数据修改,key支持path
  17. this.$forceUpdate({
  18. 'info.name': 'b'
  19. }, () => {
  20. console.log('视图更新后执行')
  21. })
  22. // 如果不传入任何数据,那么默认情况下会将data & computed 所有数据都传入视图层进行渲染
  23. this.$forceUpdate(() => {
  24. console.log('视图更新后执行')
  25. })
  26. }
  27. })

$set、$remove

正常情况下,对一个响应式数据的新增属性或者删除数据操作是没法感知的,通过 this.$set、this.$remove 可以动态添加或删除属性,并且会触发观察器更新(视图更新 | watch回调)

  1. import {createComponent} from '@mpxjs/core'
  2. createComponent({
  3. data: {
  4. info: {
  5. name: 'a'
  6. }
  7. },
  8. watch: {
  9. 'info.age' (val) {
  10. // 当新增age属性之后执行
  11. console.log(val)
  12. },
  13. 'info' (val) {
  14. // 当新增或删除属性之后都会执行
  15. console.log(val)
  16. }
  17. },
  18. attached () {
  19. // 新增age属性
  20. this.$set(this.info, 'age', 100)
  21. // 删除name属性
  22. this.$remove(this.info, 'name')
  23. }
  24. })