DEV Community

Cover image for How to create dynamic input using Vue
Snehal Rajeev Moon
Snehal Rajeev Moon

Posted on

How to create dynamic input using Vue

Hello Readers,

In this blog, I am going to show you, how we can create dynamic input using vuejs.

First, create a component and name it as DynamicInput.vue and add the below code.

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <div class="w-full mt-4 p-10">
      <button
        type="button"
        class="flex justify-start ml-2 rounded-md border px-3 py-2 bg-pink-600 text-white"
        @click="addMore()"
      >
        Add More
      </button>
      <div v-for="(course, index) in courses" :key="index">
        <div class="flex justify-start ml-2 mt-4">
          <input
            v-model="course.courseName"
            placeholder="enter you course name"
            class="w-full py-2 border border-indigo-500 rounded"
          />
          <button
            type="button"
            class="ml-2 rounded-md border px-3 py-2 bg-red-600 text-white"
            @click="remove(index)"
            v-show="index != 0"
          >
            Remove
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
  data() {
    return {
      courses: [
        {
          courseName: "",
        },
      ],
    };
  },
  methods: {
    addMore() {
      this.courses.push({
        courseName: "",
      });
    },
    remove(index) {
      this.courses.splice(index, 1);
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
Enter fullscreen mode Exit fullscreen mode

Now add this component into App.vue file as below.

<template>
  <div id="app">
    <DynamicInput msg="Example of Dynamic Input" />
  </div>
</template>

<script>
import DynamicInput from "./components/DynamicInput";

export default {
  name: "App",
  components: {
    DynamicInput,
  },
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
Enter fullscreen mode Exit fullscreen mode

I have installed tailwind CSS to styling you have to install it.

If you like my post please follow me to get more blog posts.

[deleted user] image

[Deleted User]

For more details you can refer below codesandbox.

Happy Reading. 🦄 ❤️

Top comments (1)

Collapse
 
nn6v6nn profile image
Richard Kwok

use v-show keep at least one input box on form