作者:kouchao
原文链接:https://juejin.im/post/6859251122805145607
喜欢这篇文章的希望大家可以到https://github.com/kouchao/wxue为项目点个star~(点击阅读原文即可到达)
使用
使用起来应该像是这个样子
wxue(options)
配置应该是包含一个setup
选项是一个函数,返回的函数可以this.xxx
调用,返回的数据可以this.data.xxx
用到,如下
import { wxue, reactive } from 'wxue'
wxue({
setup(options) {
const test = reactive({
x: 1,
y: 2,
})
setInterval(() => {
test.x++
}, 1000)
return {
test,
}
},
})
ref
应该有如下api
reactive
ref
unref
toRef
toRefs
computed
watchEffect
watch
各种钩子,与小程序生命周期一致
import { wxue, nextTick, ref, onShow } from 'wxue'
function useAutoAdd(x) {
const b = ref(x)
setInterval(() => {
b.value++
}, 1000)
return b
}
wxue({
data: {},
setup(options) {
const b = useAutoAdd(2)
onShow(() => {
console.log('onShow form hooks', this)
})
function getXx() {
console.log(this, 'getXx')
}
return {
c: b,
getXx,
test,
}
},
onLoad: function (options) {
setTimeout(() => {
this.test()
console.log(this.data.b)
}, 5000)
this.getXx()
},
test: function () {
nextTick(() => {
console.log(this.data.a.b)
})
this.data['a.b'] = 111
this.data['a.c'] = 111
},
})
跟 vue 的 composition-api 类似,小程序端的逻辑复用的解决方案。
由于参照vue
,暂且叫他wxue吧。提供了vue
的composition-api
类似的用法。wxue源码 跪求star~
npm i wxue -S
wxue(options)
options
中需要配置setup
,并且setup
是一个函数
返回一个对象,可包含对象或者是函数,函数将会挂载到this
中,对象将挂载到data
中
返回对象的响应数据。
import { wxue, reactive } from 'wxue'
wxue({
setup(options) {
const test = reactive({
x: 1,
y: 2,
})
setInterval(() => {
test.x++
}, 1000)
return {
test,
}
},
})
接受一个内部值并返回一个反应性且可变的ref
对象。ref
对象具有.value
指向内部值的单个属性。
import { wxue, ref } from 'wxue'
wxue({
setup(options) {
const x = ref(1)
setInterval(() => {
x.value++
}, 1000)
return {
x,
}
},
})
如果参数是 ref,则返回内部值,否则返回参数本身。
可用于 ref 在源反应对象上为属性创建
const test = reactive({
x: 1,
y: 2,
})
const x = toRef(test, 'x')
return { x }
将反应对象转换为普通对象,其中所得对象的每个属性都 ref 指向原始对象的相应属性,可用于解构
const test = reactive({
x: 1,
y: 2,
})
const { x } = toRefs(test)
return { x }
计算属性 返回的值返回一个不变的反应性 ref 对象。
const computedX = computed(() => x.value + 1)
return { computedX }
它会在反应性地跟踪其依赖关系时立即运行一个函数,并在依赖关系发生更改时重新运行它。stop 停止监听
const count = ref(0)
const stop = watchEffect(() => console.log(count.value))
setTimeout(() => {
count.value++
if (count.value === 100) {
stop()
}
}, 1000)
观察者数据源可以是返回值的 getter 函数,也可以直接是 ref, stop 停止监听
const count = ref(0)
const state = reactive({ count: 0 })
const stop = watch(ref, (count, prevCount) => {
/* ... */
})
const stop2 = watch(
() => state.count,
(count, prevCount) => {
/* ... */
}
)
stop()
stop2()
支持小程序的所有生命周期 onLoad
,onReady
,onShow
,onHide
,onUnload
,onPullDownRefresh
,onReachBottom
,onShareAppMessage
import { wxue, onShow } from 'wxue'
wxue({
setup(options) {
onShow(() => {
console.log('onShow form hooks')
})
},
})
优化的setData
,多次调用将合并成一次执行
setData
是异步的,在setData
执行后完成后执行的回调nextTick
// 1 返回Promise
await nextTick()
// 2 执行回调
nextTick(() => {})
对this.data
的 set 进行了劫持,会调用setData
欢迎大家提出宝贵的意见,如有错误还望评论区不要客气,大家共同学习,一起进步。github: https://github.com/kouchao/wxue,跪求star~
最后
欢迎加我微信(winty230),拉你进技术群,长期交流学习...
欢迎关注「前端Q」,认真学前端,做个专业的技术人...
点个在看支持我吧