vue2项目中使用 @vue/composition-api,h5发现没有任何问题,打包成app就出现了computed无法更新的问题
import { computed, ref } from '@vue/composition-api'
import { onPageScroll } from '@dcloudio/uni-app'
export function usePageScroll() {
const top = ref(0)
onPageScroll(e => {
top.value = e.scrollTop
})
return top
}
const navigationBarHeight = uni.getSystemInfoSync().statusBarHeight || 44
export function useNavbarOpacity(navHeight = navigationBarHeight) {
const scrollTop = usePageScroll()
return computed(() => Math.min(navHeight, scrollTop.value) / navHeight)
}
在app里面就发现导航栏的背景颜色无法随着滚动变透明
后面改成 watch+ref就解决了(不知道什么原因)最终解决方案
vue-composition-plugin.js,在main.ts最开头一行引用,覆盖默认的computed方法
import Vue from 'vue' import * as VueCompositionAPI from '@vue/composition-api' const watch = VueCompositionAPI.watch const ref = VueCompositionAPI.ref // app-plus 有bug 直接使用计算属性,计算属性不会自动更新 // 修复 app 端使用 computed时,第二次修改相关 getter里面的值的时候 // computed 的值不会更新,去掉原先计算属性的懒加载效果 // 强制使用watch加ref实现类似 computed VueCompositionAPI.computed = function(options){ let getter = options let setter if (typeof options === 'object') { getter = options.get setter = options.set } let initVal const refVal = ref(initVal) watch(()=> { initVal = getter() return initVal }, (newVal,oldVal)=>{ setter && setter(newVal,oldVal) refVal.value = newVal }, {deep:true,immediate:true})
return refVal
}
Vue.use(VueCompositionAPI.default)
0 个评论
要回复文章请先登录或注册