0

Ive got a simple edit screen set up here, and I don't know why its not hiding the form when I click save or cancel.

Form is being showing with a simple directive selected.name == p.name in a loop. When I unset the selected object, its not updating the DOM.

The Form contents are saving to the array, as you can see if you make some changes, click save, and then click a new row. But the form wont hide on cancel or on save.

Hopefully its something simple that I am overlooking.

Thanks

var vm = new Vue({
  el: '#vue-instance',
  data: {
    selected: {
    	name:'',
    	price: 0
    },
    products: [
      {name: 'Hamburger', price: 3.00},
      {name: 'Taco', price: 1.00},
      {name: 'Soda', price: 1.40},
      {name: 'French Fries', price: 2.00}
    ]
  },
  methods: {
      save: function(index){
          this.products[index] = this.selected;
          this.selected = {
              name:'',
              price: 0
    	  };
      }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.min.js"></script>
<div id="vue-instance">
  <ul>
    <li v-for="p, i in products" @click="selected = p">
      <span v-show="!selected || selected.name !== p.name">
        {{ p.name }}: ${{ p.price }}
      </span>
      <span v-show="selected && selected.name == p.name">
        <input type="text" v-model.lazy="selected.name" />
        <input type="text" v-model.lazy="selected.price" />
        <button @click="save(i)">Save</button>
        <button @click="selected = {}">Cancel</button>
      </span>
    </li>
  </ul>
</div>

1 Answer 1

2

The issue is the li is always running its click event handler even when you click on a button so selected will always be reassigned to the current product.

To fix it, do one of the fllowing:

  • Replace @click with @click.stop on each of the buttons to prevent the event from propagating up to the li.

  • remove the @click="selected = p" from the li and add it to the first span. This way the handler will only be run when the form is not present.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! You are my hero.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.