如何解决Vue.js 中的静态道具验证
在 Vue 中使用 props 验证时,它只在浏览器控制台中显示运行时的错误。
但我想让 props 验证在静态代码分析阶段(linting)工作。
例如,我使用了默认的 Vue 2 项目模板:
HelloWorld.vue
是具有 msg
属性的组件,它是必需的:
<template>
<h1>Message: {{ msg }}</h1>
</template>
<script>
export default {
name: 'HelloWorld',props: {
msg: {
type: String,required: true,},};
</script>
App.vue
正在使用 HelloWorld
组件,但未指定 msg
属性。相反,它使用不存在的 prop something
:
<template>
<HelloWorld :something="somewhat" />
</template>
<script>
import HelloWorld from './components/HelloWorld.vue';
export default {
name: 'App',components: {
HelloWorld,};
</script>
我希望在运行 npm run lint
时至少满足其中一些要求:
- 应该说
Error: required "msg" prop not found
- 应该说
Warning: unkNown "something" prop has been used
- 此外,如果我将
String
以外的其他内容分配给msg
道具,它应该说Error: prop "msg" should be String,but received *NotString*
换句话说,我希望 Vue 模板是 lintable 的,就像 React 中的 JSX 模板一样。
有什么办法可以在 Vue 2 或 Vue 3 中实现这一点吗?也许,一些 eslint 插件?
如果可以使用 TypeScript 解决这个问题,那就太棒了。
解决方法
这个问题的一个解决方案是使用 JSX (TSX),在 Vue 2 和 Vue 3 中都适用。
这是一个 Vue 3 示例:
HelloWorld.tsx
:
import { defineComponent } from "vue";
export default defineComponent({
name: "HelloWorld",props: {
msg: {
type: String,required: true,},setup: (props) => () => <h1>{props.msg}</h1>,});
App.tsx
:
import { defineComponent } from "vue";
import HelloWorld from "./components/HelloWorld";
export default defineComponent({
name: "App",render: () => <HelloWorld msg={"123"} />,});
这是 Vue 2 示例存储库:https://github.com/Maxim-Mazurok/vue-2-tsx-example
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。