script增强特性

    计算属性是一个纯函数,利用组合其它数据的方式返回一个新的数据,你可以像绑定普通数据一样在模板中绑定计算属性。

    示例:

    例如:

    1. <template>
    2. <view>
    3. <view>{{question}}</view>
    4. <view>{{answer}}</view>
    5. </view>
    6. </template>
    7. <script>
    8. import {createComponent} from '@mpxjs/core'
    9. createComponent({
    10. data: {
    11. question: 'old',
    12. answer: 'I cannot give you an answer until you ask a question!',
    13. info: {
    14. name: 'a'
    15. },
    16. arr: [{
    17. age: 1
    18. }]
    19. },
    20. watch: {
    21. // 如果 `question` 发生改变,这个函数就会运行
    22. question: function (newval, oldval) {
    23. },
    24. question: {
    25. handler (newval, oldval) {
    26. console.log(newval, ':', oldval) // test:old
    27. this.answer = 'Waiting for you to stop typing...'
    28. },
    29. imeediate: true // 立即执行一次
    30. // deep: true // 是否深度观察
    31. // sync: true // 数据变化之后是否同步执行,默认是进行异步队列
    32. },
    33. 'info.name' (val) {
    34. // 支持路径表达式
    35. console.log(val) // b
    36. },
    37. 'arr[0].age' (val) {
    38. // 支持路径表达式
    39. console.log(val) // 100
    40. },
    41. 'question, answer' (val, old) {
    42. // 同时观察多个值, val为数组个数, question变化时
    43. console.log(val) // ['test', 'I cannot give you an answer until you ask a question!']
    44. }
    45. },
    46. attached () {
    47. // 3s之后修改数据
    48. setTimeout(() => {
    49. }, 3000)
    50. },
    51. changeData() {
    52. this.question = 'test'
    53. this.info.name = 'b'
    54. this.arr[0].age = 100
    55. }
    56. }
    57. })
    58. </script>

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

    示例:

    1. <template xmlns="">
    2. <view class="list">
    3. <view wx:for="{{list}}">{{item}}</view>
    4. </view>
    5. </template>
    6. <script>
    7. import {createComponent} from '@mpxjs/core'
    8. import mixin from './mixin'
    9. createComponent({
    10. mixins: [mixin],
    11. ready () {
    12. console.log('component ready:', this.list.tv)
    13. }
    14. })
    15. </script>

    输出结果为