npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ophiuchus/form

v1.0.1

Published

### 介绍

Downloads

4

Readme

Form 表单

介绍

用于数据录入、校验,支持输入框、单选框、复选框、文件上传等类型,需要与 Field 输入框 组件搭配使用。

引入

import Vue from 'vue';
import Form from '@ophiuchus/form';
import Field from '@ophiuchus/field';

Vue.use(Form);
Vue.use(Field);

代码演示

基础用法

在表单中,每个 Field 组件 代表一个表单项,使用 Field 的 rules 属性定义校验规则。

<sf-form @submit="onSubmit">
  <sf-field
    v-model="username"
    name="用户名"
    label="用户名"
    placeholder="用户名"
    :rules="[{ required: true, message: '请填写用户名' }]"
  />
  <sf-field
    v-model="password"
    type="password"
    name="密码"
    label="密码"
    placeholder="密码"
    :rules="[{ required: true, message: '请填写密码' }]"
  />
  <div style="margin: 16px;">
    <sf-button round block type="info" native-type="submit">提交</sf-button>
  </div>
</sf-form>
export default {
  data() {
    return {
      username: '',
      password: '',
    };
  },
  methods: {
    onSubmit(values) {
      console.log('submit', values);
    },
  },
};

校验规则

通过 rules 定义表单校验规则,可用字段见下方表格

<sf-form validate-first @failed="onFailed">
  <!-- 通过 pattern 进行正则校验 -->
  <sf-field
    v-model="value1"
    name="pattern"
    placeholder="正则校验"
    :rules="[{ pattern, message: '请输入正确内容' }]"
  />
  <!-- 通过 validator 进行函数校验 -->
  <sf-field
    v-model="value2"
    name="validator"
    placeholder="函数校验"
    :rules="[{ validator, message: '请输入正确内容' }]"
  />
  <!-- 通过 validator 进行异步函数校验 -->
  <sf-field
    v-model="value3"
    name="asyncValidator"
    placeholder="异步函数校验"
    :rules="[{ validator: asyncValidator, message: '请输入正确内容' }]"
  />
  <div style="margin: 16px;">
    <sf-button round block type="info" native-type="submit">提交</sf-button>
  </div>
</sf-form>
import Toast  from '@ophiuchus/toast';

export default {
  data() {
    return {
      value1: '',
      value2: '',
      value3: '',
      pattern: /\d{6}/,
    };
  },
  methods: {
    // 校验函数返回 true 表示校验通过,false 表示不通过
    validator(val) {
      return /1\d{10}/.test(val);
    },
    // 异步校验函数返回 Promise
    asyncValidator(val) {
      return new Promise((resolve) => {
        Toast.loading('验证中...');

        setTimeout(() => {
          Toast.clear();
          resolve(/\d{6}/.test(val));
        }, 1000);
      });
    },
    onFailed(errorInfo) {
      console.log('failed', errorInfo);
    },
  },
};

表单项类型 - 开关

在表单中使用 Switch 组件

<sf-field name="switch" label="开关">
  <template #input>
    <sf-switch v-model="switchChecked" size="20" />
  </template>
</sf-field>
export default {
  data() {
    return {
      switchChecked: false,
    };
  },
};

表单项类型 - 复选框

在表单中使用 Checkbox 组件

<sf-field name="checkbox" label="复选框">
  <template #input>
    <sf-checkbox v-model="checkbox" shape="square" />
  </template>
</sf-field>
<sf-field name="checkboxGroup" label="复选框组">
  <template #input>
    <sf-checkbox-group v-model="checkboxGroup" direction="horizontal">
      <sf-checkbox name="1" shape="square">复选框 1</sf-checkbox>
      <sf-checkbox name="2" shape="square">复选框 2</sf-checkbox>
    </sf-checkbox-group>
  </template>
</sf-field>
export default {
  data() {
    return {
      checkbox: false,
      checkboxGroup: [],
    };
  },
};

表单项类型 - 单选框

在表单中使用 Radio 组件

<sf-field name="radio" label="单选框">
  <template #input>
    <sf-radio-group v-model="radio" direction="horizontal">
      <sf-radio name="1">单选框 1</sf-radio>
      <sf-radio name="2">单选框 2</sf-radio>
    </sf-radio-group>
  </template>
</sf-field>
export default {
  data() {
    return {
      radio: '1',
    };
  },
};

表单项类型 - 步进器

在表单中使用 Stepper 组件

<sf-field name="stepper" label="步进器">
  <template #input>
    <sf-stepper v-model="stepper" />
  </template>
</sf-field>
export default {
  data() {
    return {
      stepper: 1,
    };
  },
};

表单项类型 - 评分

在表单中使用 Rate 组件

<sf-field name="rate" label="评分">
  <template #input>
    <sf-rate v-model="rate" />
  </template>
</sf-field>
export default {
  data() {
    return {
      rate: 3,
    };
  },
};

表单项类型 - 滑块

在表单中使用 Slider 组件

<sf-field name="slider" label="滑块">
  <template #input>
    <sf-slider v-model="slider" />
  </template>
</sf-field>
export default {
  data() {
    return {
      slider: 50,
    };
  },
};

表单项类型 - 文件上传

在表单中使用 Uploader 组件

<sf-field name="uploader" label="文件上传">
  <template #input>
    <sf-uploader v-model="uploader" />
  </template>
</sf-field>
export default {
  data() {
    return {
      uploader: [{ url: 'https://img4.tuhu.org/JU_d6bTpbt6kxlAcmNKCew_w660_h520.jpeg' }],
    };
  },
};

表单项类型 - 选择器

在表单中使用 Picker 组件

<sf-field
  readonly
  clickable
  name="picker"
  :value="value"
  label="选择器"
  placeholder="点击选择城市"
  @click="showPicker = true"
/>
<sf-popup v-model="showPicker" position="bottom">
  <sf-picker
    show-toolbar
    :columns="columns"
    @confirm="onConfirm"
    @cancel="showPicker = false"
  />
</sf-popup>
export default {
  data() {
    return {
      value: '',
      columns: ['杭州', '宁波', '温州', '嘉兴', '湖州'],
      showPicker: false,
    };
  },
  methods: {
    onConfirm(value) {
      this.value = value;
      this.showPicker = false;
    },
  },
};

表单项类型 - 时间选择器

在表单中使用 DatetimePicker 组件

<sf-field
  readonly
  clickable
  name="datetimePicker"
  :value="value"
  label="时间选择"
  placeholder="点击选择时间"
  @click="showPicker = true"
/>
<sf-popup v-model="showPicker" position="bottom">
  <sf-datetime-picker
    type="time"
    @confirm="onConfirm"
    @cancel="showPicker = false"
  />
</sf-popup>
export default {
  data() {
    return {
      value: '',
      showPicker: false,
    };
  },
  methods: {
    onConfirm(time) {
      this.value = time;
      this.showPicker = false;
    },
  },
};

表单项类型 - 省市区选择器

在表单中使用 Area 组件

<sf-field
  readonly
  clickable
  name="area"
  :value="value"
  label="地区选择"
  placeholder="点击选择省市区"
  @click="showArea = true"
/>
<sf-popup v-model="showArea" position="bottom">
  <sf-area
    :area-list="areaList"
    @confirm="onConfirm"
    @cancel="showArea = false"
  />
</sf-popup>
export default {
  data() {
    return {
      value: '',
      showArea: false,
      areaList: {}, // 数据格式见 Area 组件文档
    };
  },
  methods: {
    onConfirm(values) {
      this.value = values
        .filter((item) => !!item)
        .map((item) => item.name)
        .join('/');
      this.showArea = false;
    },
  },
};

表单项类型 - 日历

在表单中使用 Calendar 组件

<sf-field
  readonly
  clickable
  name="calendar"
  :value="value"
  label="日历"
  placeholder="点击选择日期"
  @click="showCalendar = true"
/>
<sf-calendar v-model="showCalendar" @confirm="onConfirm" />
export default {
  data() {
    return {
      value: '',
      showCalendar: false,
    };
  },
  methods: {
    onConfirm(date) {
      this.value = `${date.getMonth() + 1}/${date.getDate()}`;
      this.showCalendar = false;
    },
  },
};

API

Props

| 参数 | 说明 | 类型 | 默认值 | | --- | --- | --- | --- | | label-width | 表单项 label 宽度,默认单位为px | number | string | 6.2em | | label-align |  表单项 label 对齐方式,可选值为 center right | string | left | | input-align | 输入框对齐方式,可选值为 center right | string | left | | error-message-align | 错误提示文案对齐方式,可选值为 center right | string | left | | validate-trigger | 表单校验触发时机,可选值为 onChangeonSubmit,详见下表 | string | onBlur | | colon | 是否在 label 后面添加冒号 | boolean | false | | disabled | 是否禁用表单中的所有输入框 | boolean | false | | readonly | 是否将表单中的所有输入框设置为只读 | boolean | false | | validate-first | 是否在某一项校验不通过时停止校验 | boolean | false | | scroll-to-error | 是否在提交表单且校验不通过时滚动至错误的表单项 | boolean | false | | show-error | 是否在校验不通过时标红输入框 | boolean | true | | show-error-message | 是否在校验不通过时在输入框下方展示错误提示 | boolean | true | | submit-on-enter | 是否在按下回车键时提交表单 | boolean | true |

表单项的 API 参见:Field 组件

Rule 数据结构

使用 Field 的rules属性可以定义校验规则,可选属性如下:

| 键名 | 说明 | 类型 | | --- | --- | --- | | required | 是否为必选字段 | boolean | | message | 错误提示文案 | string | (value, rule) => string | | validator | 通过函数进行校验 | (value, rule) => boolean | Promise | | pattern | 通过正则表达式进行校验 | RegExp | | trigger | 本项规则的触发时机,可选值为 onChangeonBlur | string | | formatter | 格式化函数,将表单项的值转换后进行校验 | (value, rule) => any |

validate-trigger  可选值

通过 validate-trigger 属性可以自定义表单校验的触发时机。

| 值 | 描述 | | -------- | ------------------------------------ | | onSubmit | 仅在提交表单时触发校验 | | onBlur | 在提交表单和输入框失焦时触发校验 | | onChange | 在提交表单和输入框内容变化时触发校验 |

Events

| 事件名 | 说明 | 回调参数 | | --- | --- | --- | | submit | 提交表单且验证通过后触发 | values: object | | failed | 提交表单且验证不通过后触发 | errorInfo: { values: object, errors: object[] } |

方法

通过 ref 可以获取到 Form 实例并调用实例方法,详见组件实例方法

| 方法名 | 说明 | 参数 | 返回值 | | --- | --- | --- | --- | | submit | 提交表单,与点击提交按钮的效果等价 | - | - | | validate | 验证表单,支持传入 name 来验证单个或部分表单项 | name?: string | string[] | Promise | | resetValidation | 重置表单项的验证提示,支持传入 name 来重置单个或部分表单项 | name?: string | string[] | - | | scrollToField | 滚动到对应表单项的位置,默认滚动到顶部,第二个参数传 false 可滚动至底部 | name: string, alignToTop: boolean | - |

Slots

| 名称 | 说明 | | ------- | -------- | | default | 表单内容 |

常见问题

点击表单中的普通按钮为什么会触发表单提交?

在表单中,除了提交按钮外,可能还有一些其他的功能性按钮,如发送验证码按钮。在使用这些按钮时,要注意将native-type设置为button,否则会触发表单提交。

<sf-button native-type="button">发送验证码</sf-button>

这个问题的原因是浏览器中 button 标签 type 属性的默认值为submit,导致触发表单提交。我们会在下个大版本中将 type 的默认值调整为button来避免这个问题。