2

What I am trying to achieve is a component that deals conditionally with new input or old input(edit). I've tried this, inspired by this question:

<input type="text" placeholder="New Event" v-model="event.title ? event.title : title" required/>

or even

<input type="text" placeholder="New Event" v-model="event.title || title" required/>

but both don't work. I get errors in the console.

event.title comes from prop event;

title is a property in the data object with the value of ''.

In Vue 2 do I need to build 2 separate components? One for new input and another for editing?

viery365
  • 935
  • 2
  • 12
  • 30

2 Answers2

4

You can try this one, it works for me :

  <td>
    <div v-if="event">
      <input v-model="event.title">
    </div>
    <div v-else><input v-model="title"></div>
  </td>
1

I think you can use computed for this purpose like below :

<input type="text" placeholder="New Event" v-model="nameOfMethod" required/>

and within computed methods create nameOfMethod with your logic like this :

computed:{
    nameOfMethod(){
        if (this.event.title  === "")
            return this.title;
        else
            return this.event.title;
    },

}
Thamer
  • 1,896
  • 2
  • 11
  • 20
  • Unfortunately, this does not work. The computed property would return the initial value of the input, but the input would not be able cause an update of the variable through `v-model`. – tony19 Oct 07 '18 at 11:03
  • @tony19 what do you mean by "the input would not be able cause an update of the variable .. ?" if he passes `event.title`, I don't think he will update it anyway – Thamer Oct 07 '18 at 11:15
  • The purpose of `v-model` is to allow two-way binding of a property. See [docs](https://vuejs.org/v2/guide/forms.html#Basic-Usage). – tony19 Oct 07 '18 at 11:16
  • @Thamerbelfkih I agreed with tony19 cz i tried it too before and it failed to work –  Oct 07 '18 at 11:17