Vue.js 中的简单多步骤表单。添加课程

问题描述 投票:0回答:1

这是一个用 Vue.js 编写的简单的多步骤表单。 如果出现错误,如何修改代码以将“错误”类添加到“输入文本”。我将非常感谢您的帮助。

P.S

问题应该很短,但 stackoverflow 需要在我的问题中提供更多文本。问题的长度必须与代码量成正比:)

问候,康拉德

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>My Website</title>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
  </head>
  <body>
    <main>
      <form id="app">
        <span v-for="e in errors">{{ e }}</span>
        <section v-if="step == 1">
          <h3>Step 1</h3>
          <input v-model="form.name" type="text" name="name" placeholder="Type your name">
        </section>

        <section v-if="step == 2">
          <h3>Step 2</h3>
            <input v-model="form.phone" type="tel" name="phone" placeholder="Type your phone number">
            <input v-model="form.email" type="email" name="email" placeholder="Type your email">          
        </section>

        <section v-if="step == 3">
          <h3>Step 3</h3>
            <textarea v-model="form.message" placeholder="Type message"></textarea>          
        </section>
        <button v-if="step != 1" @click.prevent="prevStep" >Prev Step</button>
        <button v-if="step != totalsteps" @click.prevent="nextStep" >Next Step</button>

      </form>
    </main>

  <script>
    
    const App = new Vue({

      el:"#app",

        data: {

          step: 1,
          totalsteps: 3,
          errors: [],

          form: {
            name: null,
            email: null,
            phone: null,
            message: null
          }

        },

      methods: {

        nextStep:function(){

          if(this.step == 1)
          {
            if(!this.form.name)
            {
              this.errors = 'Type your name'
              return false;
            }
          }

          if(this.step == 2)
          {
            if(!this.form.phone)
            {
              this.errors = 'Type your phone';
              return false;
            }
            if(!this.form.email)
            {
              this.errors = 'Type your email'
              return false;
            }
          }

          this.errors = null;

          this.step++;

        },

        prevStep:function(){

          this.step--;

        }

      }

    });

  </script>

  <style type="text/css">
    .error {
      background-color: red;
    }
  </style>
  
  </body>
</html>

vue.js vuejs2 vuejs3
1个回答
0
投票

您可以像这样绑定类:

<div :class="{ 'has-error': e }"></div>

或者,如果您想添加多个类,您可以这样做:

<div :class="['some-other-class', { 'has-error': e }]"></div>
© www.soinside.com 2019 - 2024. All rights reserved.