我正在使用vue + vuetify +打字稿来构建登录/注册表单。 根据vuetify https://vuetifyjs.com/en/components/forms#creating-rules的官方文档,可以添加自定义规则。
我的问题是:是否可以将此规则作为类,函数等提取到单独的文件中,可以从模板进行参数化以重复使用?
答案 0 :(得分:0)
您可以将规则写入外部文件。以下是规则位于js变量中的示例:
import ReactDOM from "react-dom";
import React, {
useRef,
useMemo,
useEffect,
useState,
useCallback
} from "react";
const Child = React.memo(({ onClick, suffix }) => {
const numRendersRef = useRef(1);
useEffect(() => {
numRendersRef.current++;
});
return (
<div onClick={() => onClick(suffix)}>
Click Me to log a and {suffix} and change b. Number of Renders:{" "}
{numRendersRef.current}
</div>
);
});
function App(props) {
const [a, setA] = useState("aaa");
const [b, setB] = useState("bbb");
const computeSomethingExpensiveBasedOnA = () => {
console.log("recomputing expensive thing", a);
return a + b;
};
const somethingExpensiveBasedOnA = computeSomethingExpensiveBasedOnA();
const memoizedSomethingExpensiveBasedOnA = useMemo(
() => computeSomethingExpensiveBasedOnA(),
[a]
);
const nonMemoizedCallback = suffix => {
console.log(a + suffix);
setB(prev => prev + "b");
};
const memoizedCallback = useCallback(nonMemoizedCallback, [a]);
const memoizedCallbackUsingMemo = useMemo(() => nonMemoizedCallback, [a]);
return (
<div>
A: {a}
<br />
B: {b}
<br />
nonMemoizedCallback === memoizedCallback:{" "}
{String(nonMemoizedCallback === memoizedCallback)}
<br />
somethingExpensiveBasedOnA: {somethingExpensiveBasedOnA}
<br />
memoizedSomethingExpensiveBasedOnA: {memoizedSomethingExpensiveBasedOnA}
<br />
<br />
<div onClick={() => setA(a + "a")}>Click Me to change a</div>
<br />
<Child onClick={nonMemoizedCallback} suffix="1" />
<Child onClick={memoizedCallback} suffix="2" />
<Child onClick={memoizedCallbackUsingMemo} suffix="3" />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Vue.use(Vuetify)
// or : import externalRules from '@/rules/MyRules.js'
var externalRules = [
v => !!v || 'Name is required',
v => (v && v.length <= 10) || 'Name must be less than 10 characters'
]
new Vue({
el: "#app",
data: {
valid: true,
name: '',
nameRules: externalRules
},
methods: {
validate() {
if (this.$refs.form.validate()) {
this.snackbar = true
}
},
reset() {
this.$refs.form.reset()
},
resetValidation() {
this.$refs.form.resetValidation()
}
}
})