Start with a BB

A form component of elementUI that comes with form validation rules. It’s convenient enough, but I want to encapsulate it.

Commonly used form types, mainly including: Radio menu box, input box, drop-down box.

I’ve encapsulated a basic component. Put the form data in a JSON object and pass in the packaged base component. And then loop through, depending on the type of option, whether to show an input box or a drop down box, etc.

When needed in your project, you just need to install, import, and configure the JSON file.

The packaged components are brought in as common components in the Components folder of your project.

I then published the entire base form component to NPM.

Encapsulate components and publish to NPM

So how do you publish packaged components to NPM?

The first step is to create a new VUE project using a simple Webapck configuration template.

vue init webpack-simple my-project
Copy the code

Second, in the SRC folder, create a Components folder and place the wrapped BasicForm component in it.

Step 3: Create an index.js file in the root directory.

A plugin for Vue must provide a public method, install, which is called when you use the plugin, vue.use (yourPlugin). This will inject all your components into Vue globally.

import basicForm from './src/components/basicForm/index.vue';
// Register the component
basicForm.install = Vue= > Vue.component(basicForm.name, basicForm);
export default basicForm;
Copy the code

Fourth, modify the entry and output properties of the webpack.config.js configuration file

entry: process.env.NODE_ENV == 'development' ? './src/main.js' : './index.js'.output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/'.filename: 'basicForm.js'.library: 'basicForm'.// Specify the module name when you use require
    libraryTarget: 'umd'.// Specify the output format
    umdNamedDefine: true // AMD modules in the UMD build process are named. Otherwise use anonymous define
},
Copy the code

Fifth, modify the package.json file

//name is the published package name
"name": "@orzr3/basic-form"."private": false."main": "dist/basicForm.js".Copy the code

Step 6, commit the publication

First, you need to sign up for an NPM account, which is linked here:

portal

www.npmjs.com/

PS

If the mirror is set to Taobao mirror, first set back, otherwise an error will be reported

npm config set registry http://registry.npmjs.org
Copy the code

After successful registration, log in to the NPM account and enter the user name, password, and email

npm login
Copy the code

Perform publish

npm publish
Copy the code

NPM publish –access=public

npm publish --access=public
Copy the code

Once published, log on to the NPM website, click on your profile picture, and then click on the Profile option to see what plug-ins have been published.

Installation and use

The installation

npm i @orzr3/basic-form --save
Copy the code

The introduction of

import BasicForm from '@orzr3/basic-form'
Copy the code

Error resolution

Module build failed: TypeError: this.getOptions is not a function

Vue-cli build project using sass error

Module build failed: TypeError: this.getOptions is not a function

www.cnblogs.com/chenjy1225/…

The cause is that the version of sas-Loader installed is too high. You can install an earlier version of sas-Loader.

npm install sass-loader@7.31. --save-dev
Copy the code

The cause is that the version of SASS installed is too high. You can install SASS 4.0+.

npm install node-sass@4.141. --save-dev
Copy the code

Refer to the article

Encapsulate components and publish to NPM

portal

www.cnblogs.com/max-tlp/p/9…

The sample code

I don’t know if I made that clear, but at the end of the day, I’ll post the sample code for the installation.

<template>
  <div class="friends">
    <div class="friend-main">
      <h2>Based on the component</h2>
      <div class="info-box">
        <basic-form
          :ref="formModelObject.formName"
          :formModel="formModelObject.formModel"
          :refName="formModelObject.formName + 'RefName'"
          :halfFormFlag="formModelObject.halfFormFlag"
          defaultTextareaWidth="400px"
          @submit="submitForm"
        ></basic-form>
        <div class="btn-list">
          <el-button type="primary" @click="submit">Confirm the change</el-button>
          <el-button type="default" @click="reset">To fill in</el-button>
        </div>
      </div>
    </div>
  </div>
</template><script>
import BasicForm from '@orzr3/basic-form'
import { BasicInformationMixin } from "@/mixins/BasicInformationMixin";
​
export default {
  name: "Friends".mixins: [BasicInformationMixin],
  components: {
    BasicForm,
  },
  data() {
    return {
      url: {
        edit: "/sys/user/updateBaseInfo",}}; },methods: {
    submit() {
      this.$refs[this.formModelObject.formName].submit();
    },
    submitForm(object) {
      const { refName, formData } = object;
      formData.id = this.userInfo.id;
      let key = this.active;
      let httpurl = this.url.edit;
      let method = "post";
      this.$api.httpAction(httpurl, formData, method).then((res) = > {
        this.loading = false;
        if (res.code == 200) {}else {
          this.$message.error(res.msg); }}); },reset() {
      this.$nextTick(() = > {
        this.$refs[this.formModelObject.formName].resetFields(); }); }},created(){}};</script><style scoped>
</style>
Copy the code

Basicinformationmixin.js file in the mixins folder

import {
  validPhone,
  validEmail,
  validIDCard,
  validPwd,
  vaildRealName,
} from "@/utils/validate";
​
export const BasicInformationMixin = {
  data() {
    return {
      formModelObject: {
        formName: "backUp".formModel: {
          formList: [{value: "".prop: "roleName".label: "My role".placeHolder: "".disabled: true.tips: "".rules: {
                value: [{required: false.message: "".trigger: "blur",},],},}, {value: "".prop: "loginName".label: "Login Account".placeHolder: "".disabled: true.tips: "Cannot be modified. Generally used for background login name".tipsColor: '# 606266'.rules: {
                value: [{required: false.message: "".trigger: "blur",},],},}, {value: "".prop: "userName".label: "Username".placeHolder: "Please enter user name".tips: "".rules: {
                value: [{required: true.message: "Please enter user name".trigger: "blur",},],},}, {value: "".prop: "sex".label: "Gender".placeHolder: "".tips: "".type: "radio".selectOptions: [{value: '0'.text: "Male"}, {value: '1'.text: "Female"],},rules: {
                value: [{required: true.message: "Please select a gender.".trigger: "blur",},],},}, {value: "".prop: "phone".label: "Mobile phone".placeHolder: "Please enter your mobile phone number.".tips: "".rules: {
                value: [{required: false.trigger: "change".validator: validPhone,
                  },
                ],
              },
            },
            {
              value: "".prop: "email".label: "Email".placeHolder: "Please enter your email address".tips: "".rules: {
                value: [{required: false.trigger: "change".validator: validEmail,
                  },
                ],
              },
            },
            {
              value: "".prop: "remark".label: "Note".placeHolder: "Please enter remarks".type: "textarea".rules: {
                value: [{required: false.message: "Please enter remarks".trigger: "blur",},],},},},halfFormFlag: false,}}},methods: {},}Copy the code

Validate.js file in the utils folder

// Verify the latest regular expression for 2020
export const phoneReg = / ^ (13 14 [01456879] [0-9] | | 15 [0, 3, 5-9] 16 [2567] | | 17 [0 to 8] [0-9] | | 18 19 [0, 3, 5-9]) \ d {8} $/export const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
​
export const idcardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
​
export const nameReg = / ^ ([\ u4e00 - \ u9fa5] {2, 20} | [a zA - z. \ s], 20 {2}) $/;
/** * Created by PanJiaChen on 16/11/18. */
/** * email *@param {*} s* /
export function isEmail(s) {
  return / ^ ([a zA - Z0-9. _ -]) + @ ([a zA - Z0 - _ - 9]) + ((. [a zA - Z0 - _ - 9] {2, 3})} {1, 2) $/.test(s)
}
​
/** * Mobile phone number *@param {*} s* /
export function isMobile(s) {
  return / [0-9] {10} ^ 1 $/.test(s)
}
​
/** * Phone number *@param {*} s* /
export function isPhone(s) {
  return / ^ ([0-9] {3, 4} -)? [0-9] {7, 8} $/.test(s)
}
​
/** * URL *@param {*} s* /
export function isURL(s) {
  return /^http[s]? : \ \ /. * /.test(s)
}
​
/ * * *@param {string} path
 * @returns {Boolean}* /
export function isExternal(path) {
  return /^(https? :|mailto:|tel:)/.test(path)
}
​
/ * * *@param {string} str
 * @returns {Boolean}* /
export function validUsername(str) {
  const valid_map = ['admin'.'editor']
  return valid_map.indexOf(str.trim()) >= 0
}
​
/** * Verify mailbox input *@param {Validation rule} rule
 * @param {validated value} value
 * @param {callback function} callback* /
export function validPhoneOrEmail(rule, value, callback) {
  if(rule.required && ! value) {return callback(new Error('Please enter your mobile phone number/email'));
  }
  if (value === ' ' || value === null) callback()
  if (phoneReg.test(value) || emailReg.test(value)) {
    callback()
  } else {
    callback(new Error('Incorrect input of mobile phone/email format'))}}export function validPhone(rule, value, callback) {
  if(rule.required && ! value) {return callback(new Error('Please enter your mobile phone number'));
  }
  if (value === ' ' || value === null) callback()
  if (phoneReg.test(value)) {
    callback()
  } else {
    callback(new Error('Incorrect input of mobile phone number format'))}}export function validEmail(rule, value, callback) {
  if(rule.required && ! value) {return callback(new Error('Please enter email address'));
  }
  if (value === ' ' || value === null) callback()
  if (emailReg.test(value)) {
    callback()
  } else {
    callback(new Error('Incorrect email format input'))}}export function validIDCard(rule, value, callback) {
  if(rule.required && ! value) {return callback(new Error('Please enter your ID card number'));
  }
  if (value === ' ' || value === null) callback()
  if (idcardReg.test(value)) {
    callback()
  } else {
    callback(new Error('Wrong id number'))}}export function vaildRealName(rule, value, callback){
  if(rule.required && ! value) {return callback(new Error('Please enter your real name'));
  }
  if (value === ' ' || value === null) callback()
  if (nameReg.test(value)) {
    callback()
  } else {
    callback(new Error('Incorrect real name'))}}/* Verify password */
export function validPwd(rule, value, callback) {
  if(rule.required && ! value) {return callback(new Error('Please enter your password (password must be larger than 8 characters, consisting of numbers, letters and special characters)'));
  }
  if (value === ' ' || value === null) callback();
  /* js regular check password. The password must be 8-16 bits */
  // let rules = /^(? ! ([0-9] + $)? ! [a zA - Z] + $) [0-9 a zA - Z] $/ 16th {8}
  let rules = / ^ (? =.*[a-zA-Z])(? =.*\d)(? =. * [~! @ # $% ^ & * () _ + ` \ = {} : "' < >?,. /]). {8} $/;
  if (rules.test(value)) {
    callback()
  } else {
    callback(new Error('Password is made up of 8 digits, letters and special symbols! '))}}Copy the code