custom-ref.uvue 982 字节
Newer Older
DCloud-WZF's avatar
DCloud-WZF 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 <template>
   <view class="page">
     <text id="state-count">state.count: {{state['count']}}</text>
     <button class="uni-common-mt" id="increment-btn" @click="increment">increment state.count</button>
     <button class="uni-common-mt" id="trigger-ref-btn" @click="triggerRefState">triggerRef state</button>
   </view>
 </template>

 <script setup>
  const useCustomRef = (value : UTSJSONObject) : Ref<UTSJSONObject> => {
    return customRef((track, trigger) : UTSJSONObject => {
      return {
        get() : UTSJSONObject {
          track()
          return value
        },
        set(newValue : UTSJSONObject) {
          value = newValue
          trigger()
        }
      }
    })
  }

  const state = useCustomRef({ count: 0 })

  const increment = () => {
    (state.value as UTSJSONObject)['count'] = ((state.value as UTSJSONObject)['count'] as number) + 1
  }
  const triggerRefState = () => {
    triggerRef(state)
  }
 </script>