custom-ref.uvue 1.0 KB
Newer Older
DCloud-WZF's avatar
DCloud-WZF 已提交
1 2 3
 <template>
   <view class="page">
     <text id="state-count">state.count: {{state['count']}}</text>
4 5
     <button class="uni-common-mt increment-btn" @click="increment">increment state.count</button>
     <button class="uni-common-mt trigger-ref-btn" @click="triggerRefState">triggerRef state</button>
DCloud-WZF's avatar
DCloud-WZF 已提交
6 7 8 9
   </view>
 </template>

 <script setup>
DCloud-WZF's avatar
DCloud-WZF 已提交
10 11 12
  const useCustomRef = (value : UTSJSONObject) : Ref<UTSJSONObject> => {
    // @ts-ignore
    return customRef<UTSJSONObject>((track, trigger) : UTSJSONObject => {
DCloud-WZF's avatar
DCloud-WZF 已提交
13 14 15 16 17 18 19 20 21
      return {
        get() : UTSJSONObject {
          track()
          return value
        },
        set(newValue : UTSJSONObject) {
          value = newValue
          trigger()
        }
DCloud-WZF's avatar
DCloud-WZF 已提交
22
      } as UTSJSONObject
DCloud-WZF's avatar
DCloud-WZF 已提交
23 24 25
    })
  }

DCloud-WZF's avatar
DCloud-WZF 已提交
26
  const state = useCustomRef({ count: 0 } as UTSJSONObject)
DCloud-WZF's avatar
DCloud-WZF 已提交
27 28 29 30 31 32 33 34

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