0.2.1 • Published 4 years ago
vuebest-pi v0.2.1
Pi
Best practice of use functions essential Vue Composition API
📦 Install
$ npm install vuebest-pi
$ yarn add vuebest-pi
⚡ Functions
- createPi
- packProvide
- useAsync
- useAutoCount
Usage
1. createPi
// js ts
const count = ref(0)
function setCount(value) {
count.value = value
}
const [countProvide, countInject] = createPi({count, setCount})
export {
countProvide, countInject
}
// vue component, use in setup
countProvide()
// vue component, after provide, use in setup
const {count, setCount} = countInject()
return {count, setCount}
// after return: count, setCount can be used in vue template html element
2. packProvide
// js, ts
const [countProvide, countInject] = createPi({count, setCount})
const [userProvide, userInject] = createPi({user, setUser})
const useProvide = packProvide(countProvide, userProvide)
// useProvide once only
export {
useProvide, countInject, userInject
}
3. useAsync
async function getCount() {
const result = await ajax.get('count')
return !!result
}
// default value
// loading : false
// error: false
// The "getcount" function must be a function that returns promise.
// "getCount" return Promise.reject then "error" is true,
// returns Promise.resolve then "error" is false.
// "loading" is true during getCountAction execution and false after execution.
// 1000, Timeout 1000ms. Only affects the loading,
// error changes do not affect the implementation of the getcount
// getCount函数必须为返回Promise的函数。
// getCount返回Promise.reject则error为true,返回Promise.resolve则error为false。
// getCountAction执行中loading为true,执行后loading为false。
// 1000, timeout 1000ms. 只影响loading, error的改变,不影响getCount的执行
const [loading, error, getCountAction] = useAsync(getCount, 1000)
4. useAutoCount
<template>
<span
v-if="ready"
@click.stop="startCount"
>获取验证码 | getVerifyCount</span>
<span v-if="!ready">重新获取 | re get {{ count }}s</span>
</template>
<script>
import {useAutoCount} from 'vuebest-pi'
export default {
// use in setup
setup() {
/*
* @ready: true -> 未开始计数,false -> 正在计数中
* @count: Ref<number> -> 自动计数的值
* @startCount: 开始自动计数
* @stopCount: 停止自动计数
* @60: 从60开始计数
* @0: 计数到0自动停止
* @1000: 每1000ms自动计数,-+step默认为1
*/
const {ready, count, startCount, stopCount} = useAutoCount(60, 0, 1000)
return {
ready, count,
startCount,
stopCount,
}
}
}
</script>