When using props validation in Vue, it only shows errors during the runtime in the browser console.
But I want to get props validation to work during the static code analysis phase (linting).
For example, I have used the default Vue 2 project template:
HelloWorld.vue
is the component that has msg
prop and it's required:
<template>
<h1>Message: {{ msg }}</h1>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: {
type: String,
required: true,
},
},
};
</script>
App.vue
is using HelloWorld
component, but doesn't specify msg
prop. Instead, it uses non-existent prop something
:
<template>
<HelloWorld :something="somewhat" />
</template>
<script>
import HelloWorld from './components/HelloWorld.vue';
export default {
name: 'App',
components: {
HelloWorld,
},
};
</script>
I expect at least some of these requirements to be met when I run npm run lint
:
Error: required "msg" prop not found
Warning: unknown "something" prop has been used
String
to msg
prop, it should say Error: prop "msg" should be String, but received *NotString*
In other words, I want Vue templates to be lintable, like JSX templates in React.
Is there any way I can achieve this in Vue 2 or Vue 3? Perhaps, some eslint plugins?
If this can be solved using TypeScript - that would be super awesome.
A solution to this problem, which works in both Vue 2 and Vue 3 is to use JSX (TSX).
Here's a Vue 3 example:
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"} />,
});
Here's Vue 2 example repo: https://github.com/Maxim-Mazurok/vue-2-tsx-example
And Vue 3: https://github.com/Maxim-Mazurok/vue-3-tsx-example
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.