在vue3中使用vue-router来跳转时,每次都要引入vue-router,很麻烦,使用hooks封装之后,很方便。
const REDIRECT_NAME = 'Redirect';
const BASE_PATH = '/myapp/home';
import { unref } from 'vue';
import { useRouter } from 'vue-router';
function isString(val) {
const type = Object.prototype.toString.call(val);
if (type === '[object string]') {
return true;
}
return false;
}
function handleError(e) {
console.error(e);
}
// 切换路由
export function useGo(_router) {
let router;
if (!_router) {
router = useRouter();
}
const { push, replace } = _router || router;
function go(opt, is_replace = false) {
if (!opt) return;
if (isString((opt = BASE_PATH))) {
is_replace ? replace(opt).catch(handleError) : push(opt).catch(handleError);
} else {
const o = opt;
is_replace ? replace(o).catch(handleError) : push(o).catch(handleError);
}
}
return go;
}
/**
* @description: 重新跳转当前页面
*/
export const useRedo = _router => {
const { push, currentRoute } = _router || useRouter();
const { query, params = {}, name, fullPath } = unref(currentRoute.value);
function redo() {
return new Promise(resolve => {
if (name === REDIRECT_NAME) {
resolve(false);
return;
}
if (name && Object.keys(params).length > 0) {
params['_redirect_type'] = 'name';
params['path'] = String(name);
} else {
params['_redirect_type'] = 'path';
params['path'] = fullPath;
}
push({ name: REDIRECT_NAME, params, query }).then(() => resolve(true));
});
}
return redo;
};
网友评论