首页 > 解决方案 > vue中的简单验证

问题描述

我是初学者网络开发人员。我在 vue 项目中做了我的第一个应用程序。

我有这个代码:

<template>
  <CRow>
    <CCol col="12" lg="6">
      <CCard no-header>
        <CCardBody>
          <h3>
            Create Note
          </h3>
          <CAlert
            :show.sync="dismissCountDown"
            color="primary"
            fade
          >
            ({{ dismissCountDown }}) {{ message }}
          </CAlert>

          <CInput label="Title" type="text" id="title" placeholder="Title" v-model="note.title"></CInput>

          <CInput textarea="true" label="Content" id="content" :rows="9" placeholder="Content.."
                  v-model="note.content"></CInput>

          <CInput label="Applies to date" type="date" id="applies_to_date" v-model="note.applies_to_date"></CInput>

          <CSelect id="status_id"
                   label="Status"
                   :value.sync="note.status_id"
                   :plain="true"
                   :options="statuses"
          >
          </CSelect>
          <CInput label="Note type" type="text" id="note_type" v-model="note.note_type"></CInput>

          <template>
            <div id="app">
              <ckeditor v-model="editorData" :config="editorConfig"></ckeditor>
            </div>
          </template>

          <CButton color="primary" @click="store()">Create</CButton>
          <CButton color="primary" @click="goBack">Back</CButton>
        </CCardBody>
      </CCard>
    </CCol>
  </CRow>
</template>

import axios from 'axios';
import Vue from 'vue';
import CKEditor from 'ckeditor4-vue';

Vue.use(CKEditor);

export default {
  name: 'EditUser',
  props: {
    caption: {
      type: String,
      default: 'User id'
    },
  },
  data: () => {
    return {
      note: {
        title: '',
        content: '',
        applies_to_date: '',
        status_id: null,
        note_type: '',
      },
      statuses: [],
      message: '',
      dismissSecs: 7,
      dismissCountDown: 0,
      showDismissibleAlert: false,

      editorData: '',
      editorConfig: {
        // The configuration of the editor.
        filebrowserImageBrowseUrl: Vue.prototype.$apiAdress+'/api/laravel-filemanager?token=' + localStorage.getItem("api_token"),
        filebrowserImageUploadUrl: Vue.prototype.$apiAdress+'/api/laravel-filemanager/upload?type=Images&amp;_token=&token=' + localStorage.getItem("api_token"),
        filebrowserBrowseUrl: Vue.prototype.$apiAdress+'/api/laravel-filemanager?type=Files&token=' + localStorage.getItem("api_token"),
        filebrowserUploadUrl: Vue.prototype.$apiAdress+'/api/laravel-filemanager/upload?type=Files&amp;_token=&token=' + localStorage.getItem("api_token"),
        height: 500,
        language: 'pl',
        //extraPlugins: 'facebookvideo, youtube, html5video',
        editorUrl: "facebookvideo.js",
        extraPlugins: 'a11yhelp,about,basicstyles,bidi,blockquote,clipboard,colorbutton,colordialog,contextmenu,copyformatting,dialogadvtab,div,editorplaceholder,elementspath,enterkey,entities,exportpdf,filebrowser,find,flash,floatingspace,font,format,forms,horizontalrule,htmlwriter,iframe,image,indentblock,indentlist,justify,language,link,list,liststyle,magicline,maximize,newpage,pagebreak,pastefromgdocs,pastefromlibreoffice,pastefromword,pastetext,preview,print,removeformat,resize,save,scayt,selectall,showblocks,showborders,smiley,sourcearea,specialchar,stylescombo,tab,table,tableselection,tabletools,templates,toolbar,undo,uploadimage, wysiwygarea,autoembed,image2,embedsemantic',
        image2_alignClasses: ['image-align-left', 'image-align-center', 'image-align-right'],
        image2_disableResizer: true,
      }
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1)
      // this.$router.replace({path: '/users'})
    },
    store() {
      let self = this;
      axios.post(this.$apiAdress + '/api/notes?token=' + localStorage.getItem("api_token"),
        self.note
      )
        .then(function (response) {
          self.note = {
            title: '',
            content: '',
            applies_to_date: '',
            status_id: null,
            note_type: '',
          };
          self.message = 'Successfully created note.';
          self.showAlert();
        }).catch(function (error) {
        if (error.response.data.message == 'The given data was invalid.') {
          self.message = '';
          for (let key in error.response.data.errors) {
            if (error.response.data.errors.hasOwnProperty(key)) {
              self.message += error.response.data.errors[key][0] + '  ';
            }
          }
          self.showAlert();
        } else {
          console.log(error);
          self.$router.push({path: 'login'});
        }
      });
    },
    countDownChanged(dismissCountDown) {
      this.dismissCountDown = dismissCountDown
    },
    showAlert() {
      this.dismissCountDown = this.dismissSecs
    },
  },
  mounted: function () {
    let self = this;
    axios.get(this.$apiAdress + '/api/notes/create?token=' + localStorage.getItem("api_token"))
      .then(function (response) {
        self.statuses = response.data;
      }).catch(function (error) {
      console.log(error);
      self.$router.push({path: 'login'});
    });
  }
}

当输入为空时,我需要使用警告框添加到我的项目验证中。我需要标题和内容。当用户单击“创建”按钮时,我需要检查此输入。如果它是空的 - 那么我需要显示警报()。

我怎样才能做到?

请帮我 :)

标签: javascriptvue.js

解决方案


您可以制作方法:

checkInputs() {
  if(!this.note.title) {
    this.message = 'pls enter title'
    this.showAlert()
    return true
  }
  if(!this.note.content) {
    this.message = 'pls enter content'
    this.showAlert()
    return true
  }
  return false
}

和存储方法:

store() {
  if(this.checkInputs()) return
  ...

推荐阅读