vue-json-schema (vue-json-schema)
Vue component form based on JSON Schema.
基于JSON模式的Vue组件形式。
构建设置 (Build Setup)
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# build for production and view the bundle analyzer report
npm run build --report
FormSchema API (FormSchema API)
道具 (props)
-
schema
[Object, Promise] (required) The JSON Schema object. Use thev-if
directive to load asynchronous schema.schema
[Object,Promise] ( 必需 )JSON Schema对象。 使用v-if
指令加载异步模式。 -
v-model
Object (optional)default: [object Object]
Use this directive to create two-way data bindings with the component. It automatically picks the correct way to update the element based on the input type.v-model
Object ( 可选 )default: [object Object]
使用此伪指令可与组件创建双向数据绑定。 它会根据输入类型自动选择更新元素的正确方法。 -
action
String (optional) The URI of a program that processes the form information.action
String ( 可选 )处理表单信息的程序的URI。 -
autocomplete
String (optional) This property indicates whether the value of the control can be automatically completed by the browser. Possible values are:off
andon
.autocomplete
String ( 可选 )此属性指示浏览器是否可以自动完成控件的值。 可能的值为:off
和on
。 -
enctype
String (optional)default: 'application/x-www-form-urlencoded'
When the value of the method attribute is post, enctype is the MIME type of content that is used to submit the form to the server. Possible values are: - application/x-www-form-urlencoded: The default value if the attribute is not specified. - multipart/form-data: The value used for an element with the type attribute set to "file". - text/plain (HTML5)enctype
字符串 ( 可选 )default: 'application/x-www-form-urlencoded'
当method属性的值为post时,enctype是用于将表单提交到服务器的内容的MIME类型。 可能的值为:-application / x-www-form-urlencoded:如果未指定属性,则为默认值。 -multipart / form-data:用于 类型属性设置为“文件”的元素。 -文字/纯文字(HTML5) -
method
String (optional)default: 'post'
The HTTP method that the browser uses to submit the form. Possible values are: - post: Corresponds to the HTTP POST method ; form data are included in the body of the form and sent to the server. - get: Corresponds to the HTTP GET method; form data are appended to the action attribute URI with a '?' as separator, and the resulting URI is sent to the server. Use this method when the form has no side-effects and contains only ASCII characters.method
String ( 可选 )default: 'post'
浏览器用来提交表单的HTTP方法。 可能的值为:-post:对应于HTTP POST方法; 表单数据包含在表单主体中,并发送到服务器。 -get:对应于HTTP GET方法; 表单数据以'?'附加到动作属性URI 作为分隔符,然后将结果URI发送到服务器。 当表单没有副作用并且仅包含ASCII字符时,请使用此方法。 -
novalidate
Boolean (optional) This Boolean attribute indicates that the form is not to be validated when submitted.novalidate
Boolean ( 可选 )此Boolean属性指示在提交表单时不对其进行验证。 -
input-wrapping-class
String (optional) Define the inputs wrapping class. Leaveundefined
to disable input wrapping.input-wrapping-class
字符串 ( 可选 )定义输入包装类。 保留undefined
以禁用输入换行。
大事记 (events)
-
input
Fired synchronously when the value of an element is changed.input
当元素的值更改时同步触发。 -
change
Fired when a change to the element's value is committed by the user.当用户提交对元素值的
change
触发。 -
invalid
Fired when a submittable element has been checked and doesn't satisfy its constraints. The validity of submittable elements is checked before submitting their owner form, or after thecheckValidity()
of the element or its owner form is called.invalid
在检查了可提交元素并且不满足其约束条件时触发。 在提交其所有者表单之前,或者在checkValidity()
元素或其所有者表单的checkValidity()
之后,检查可提交元素的有效性。 -
submit
Fired when a form is submittedsubmit
表单时触发
方法 (methods)
-
input(name)
Get a form input reference.input(name)
获取表单输入引用。 -
form()
Get the form reference.form()
获取表单引用。 -
reportValidity()
Returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.reportValidity()
如果元素的子控件满足其验证约束,则返回true。 返回false时,将为每个无效子级触发可取消的无效事件,并将验证问题报告给用户。 -
checkValidity()
Checks whether the form has any constraints and whether it satisfies them. If the form fails its constraints, the browser fires a cancelableinvalid
event at the element, and then returns false.checkValidity()
检查表单是否具有任何约束以及是否满足约束。 如果表单无法满足其约束条件,则浏览器将在该元素上引发可取消的invalid
事件,然后返回false。 -
reset()
Reset the value of all elements of the parent form.reset()
重置父窗体的所有元素的值。 -
submit(event)
Send the content of the form to the server.submit(event)
将表单的内容发送到服务器。 -
setErrorMessage(message)
Set a message error.setErrorMessage(message)
设置消息错误。 -
clearErrorMessage()
clear the message error.clearErrorMessage()
清除消息错误。
用法 (Usage)
Define your JSON Schema file:
定义您的JSON模式文件:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"title": "Newsletter Subscription",
"properties": {
"name": {
"type": "string",
"minLength": 8,
"maxLength": 80,
"attrs": {
"placeholder": "Full Name",
"title": "Please enter your full name"
}
},
"email": {
"type": "string",
"maxLength": 120,
"attrs": {
"type": "email",
"placeholder": "Email"
}
},
"lists": {
"type": "string",
"enum": ["Daily New", "Promotion"]
}
},
"additionalProperties": false,
"required": ["name", "email", "lists"]
}
In your Vue file:
在您的Vue文件中:
<template>
<form-schema :schema="schema" v-model="model" @submit="submit">
<button type="submit">Subscribe</button>
</form-schema>
</template>
<script>
import FormSchema from 'vue-json-schema'
import schema from './schema/newsletter-subscription.json'
export default {
data: () => ({
schema: schema,
model: {}
}),
methods: {
submit (e) {
// this.model contains the valid data according your JSON Schema.
// You can submit your model to the server here
}
},
components: { FormSchema }
}
</script>
异步模式 (Async Schema)
To asynchronously load a schema, just set a promise that returns it.
要异步加载模式,只需设置一个返回它的promise。
<script>
import axios from 'axios'
import FormSchema from 'vue-json-schema'
export default {
data: () => ({
schema: axios.get('/api/schema/subscription.json'),
}),
components: { FormSchema }
}
</script>
使用自定义表单元素 (Use custom form elements)
Use FormSchema.setComponent(type, component[, props = {}])
to define custom element to use for rendering.
使用FormSchema.setComponent(type, component[, props = {}])
定义用于渲染的自定义元素。
See vue-json-schema-demo-elementui for a complete example.
有关完整示例,请参见vue-json-schema-demo-elementui。
// an element-ui example
import FormSchema from 'vue-json-schema'
import {
Form,
FormItem,
Input,
Radio,
Checkbox,
Select,
Option,
Button
} from 'element-ui'
FormSchema.setComponent('label', FormItem)
FormSchema.setComponent('email', Input)
FormSchema.setComponent('text', Input)
FormSchema.setComponent('textarea', Input)
FormSchema.setComponent('checkbox', Checkbox)
FormSchema.setComponent('radio', Radio)
FormSchema.setComponent('select', Select)
FormSchema.setComponent('option', Option)
// Use the third argument to define props of the component
FormSchema.setComponent('button', Button, {
type: 'primary',
label: 'Subscribe'
})
// The third argument can also be a function that return an object
FormSchema.setComponent('form', Form, ({ vm }) => {
// vm is the FormSchema VM
const labelWidth = '120px'
const model = vm.data
const rules = {}
vm.fields.forEach((field) => {
rules[field.name] = {
required: field.required,
message: field.title
}
})
// returning the form props
return { labelWidth, rules, model }
})
// By default `<h1/>` is used to render the form title.
// To override this, use the `title` type:
FormSchema.setComponent('title', 'h2')
// By default `<p/>` is used to render the form description.
// To override this, use the `description` type:
FormSchema.setComponent('description', 'small')
// By default `<div/>` is used to render the message error.
// To override this, use the `error` type:
FormSchema.setComponent('error', 'el-alert', ({ vm }) => ({
type: 'error',
title: vm.error
}))
export default {
data: () => ({
schema: {...}
}),
// ...
components: { FormSchema }
}
多个复选框元素 (Multiple Checkbox elements)
To define multiple checkbox, use the JSON Schema keyword anyOf
:
要定义多个复选框,请使用JSON Schema关键字anyOf
:
schema.json
schema.json
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"multipleCheckbox": {
"type": "array",
"anyOf": [
{ "value": "daily", "label": "Daily New" },
{ "value": "promotion", "label": "Promotion" }
]
}
}
}
component.vue
component.vue
<script>
import FormSchema from 'vue-json-schema'
FormSchema.setComponent('select', 'el-select', ({ item }) => {
return { label: item.value }
})
FormSchema.setComponent('checkboxgroup', 'el-checkbox-group')
export default { ... }
</script>
分组无线电元素 (Grouped Radio elements)
To group radio elements, use the JSON Schema keyword enum
and attrs.type === 'radio'
:
要对单选元素进行分组,请使用JSON Schema关键字enum
和attrs.type === 'radio'
:
schema.json
schema.json
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"groupedRadio": {
"type": "string",
"enum": [
{ "value": "daily", "label": "Daily New" },
{ "value": "promotion", "label": "Promotion" }
],
"attrs": {
"type": "radio"
}
}
}
}
component.vue
component.vue
<script>
import FormSchema from 'vue-json-schema'
FormSchema.setComponent('select', 'el-radio', ({ item }) => {
return { label: item.value }
})
FormSchema.setComponent('radiogroup', 'el-radio-group')
export default { ... }
</script>
数组输入元素 (Array Inputs Elements)
To render a array field), define your schema like:
要呈现数组字段,请定义您的架构,如下所示:
schema.json
schema.json
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"arrayInput": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
component.vue
component.vue
vue-json-schema
will render a text input by adding a button to add more inputs.
vue-json-schema
将通过添加按钮添加更多输入来呈现文本输入。
<script>
import FormSchema from 'vue-json-schema'
// To override the default array button props
FormSchema.setComponent('arraybutton', 'button', {
native: true, // required to force button rendering as HTML native element
label: 'Add more item'
})
export default { ... }
</script>
正则表达式输入 (Regex Inputs)
To render a regex input, define your schema like:
要呈现正则表达式输入,请定义您的架构,如下所示:
schema.json
schema.json
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"regexInput": {
"type": "string",
"pattern": "[a-e]+"
}
}
}
翻译自: https://vuejsexamples.com/generate-a-form-using-json-schema-and-vue-js/