0
Follow
0
View

In Vue v2, How do I verify if a value entered into a form is empty?

daijianlin 注册会员
2023-01-24 20:50

Based on your code, you should declare a property called title in the data function and check if title is empty or not in addItem method.

var app = new Vue({
  el: '#app',
  data () {
    return {
      // errors: [],
      title: '', // add this property in data function
      items: [{
        userId: 0,
        id: 0,
        title: "",
        completed: false,
        }],
        title: '',
        show: 'all',
    }
  },
  // Using axios to asynchrously query the API
  mounted () {
    axios
      .get("https://jsonplaceholder.typicode.com/todos")
      .then(response => this.items = response.data)
  },
  computed: {
    activeItems() {
      this.saveItems;
      return this.items.filter(item => {
        return !item.completed;
      });
    },
    filteredItems() {
      // An active state denotes the task is not yet completed
      if (this.show === 'active')
        return this.items.filter(item => {
          return !item.completed;
        });
      if (this.show === 'completed')
        return this.items.filter(item => {
          return item.completed;
        });
        //  This makes it so added tasks go to the top, not bottom
      return this.items.reverse();
    },
    
  },
  methods: {
    addItem() {

      if(this.title !== '') { //check if `title` is empty or not
        this.items.push({
          title: this.title,
          completed: false
        })
        this.title = "";
      }
      else {
        alert("Please enter a task.")
      }

I created an example in Stackblitz. You can also view the example directly by clicking here

About the Author

Question Info

Publish Time
2023-01-24 20:50
Update Time
2023-01-24 20:50

Related Question