- 像react一样传递 属性和方案
自定义属性不行 因为自定义指令主要还是针对dom来的
不推荐在组件上使用自定义指令
v-xxx="obj" 编译为 把v-xxx="select"
翻译成v-bind="select.bindProps" v-on="select.bindEvents"
,只要我们开发的时候规定绑定组件的hook返回格式必须有bindProps
和bindEvents
就好了
function Demo(){
const select = useSelect({
apiFun:getDict
})
return <Select {...select}>;
}
import type { PluginOption } from "vite";
type HookBindPluginOptions = {
prefix?: string;
bindKey?: string;
eventKey?: string;
};
export const viteHookBind = (options?: HookBindPluginOptions): PluginOption => {
const { prefix, bindKey, eventKey } = Object.assign(
{
prefix: "v-ehb",
bindKey: "bindProps",
eventKey: "bindEvents",
},
options
);
return {
name: "vite-plugin-vue-component-enhance-hook-bind",
enforce: "pre",
transform: (code, id) => {
const last = id.substring(id.length - 4);
if (last === ".vue") {
if (code.indexOf(prefix) === -1) {
return code;
}
const templateStrStart = code.indexOf("<template>");
const templateStrEnd = code.lastIndexOf("</template>");
let templateStr = code.substring(templateStrStart, templateStrEnd + 11);
let startIndex;
while ((startIndex = templateStr.indexOf(prefix)) > -1) {
const endIndex = templateStr.indexOf(`"`, startIndex + 7);
const str = templateStr.substring(startIndex, endIndex + 1);
const obj = str.split(`"`)[1];
const newStr = templateStr.replace(
str,
`v-bind="${obj}.${bindKey}" v-on="${obj}.${eventKey}"`
);
templateStr = newStr;
}
return (
code.substring(0, templateStrStart) +
templateStr +
code.substring(templateStrEnd + 11)
);
}
return code;
},
};
};