0

I wanna create @click in my select menu which is empty by default. I tried to create it in select, option and even div, but it doesn't to seem work.

So, I have this code in my template:

<div style="float: right; padding-right: 13px">
        <span>
          Sort by:
        </span>
        <select v-model="sort">
          <option
            v-for="item in items"
            :key="item.id"
            :value="item"
            @click="sortBy"
            v-text="item.title"
          ></option>
        </select>
      </div>

This in data:

items: [
    {
      id: 1,
      title: 'Price: Low to High',
      sort: 1
    },
    {
      id: 2,
      title: 'Price: High to Low',
      sort: 2
    },
    {
      id: 3,
      title: 'Newest first',
      sort: 3
    },
    {
      id: 4,
      title: 'Oldest first',
      sort: 4
    }
  ],
  sort: null

And this in methods:

sortBy() {
  console.log(this.sort) // console.log for tests
},

Thanks for answers

1
  • 4
    <select v-model="sort" @change="sortBy">, or watch:{sort(){this.sortBy()}} Commented Jun 30, 2021 at 20:17

1 Answer 1

1
<div style="float: right; padding-right: 13px">
  <span>
    Sort by:
  </span>
  <select v-model="sort">
    <option
      v-for="item in sortedList" //Notice the computed var
      :key="item.id"
      :value="item"
      @click="sortBy"
      v-text="item.title"
    ></option>
  </select>
</div>

computed:{
  sortedList(){
    if(this.sort){
      //FILTER YOUR LIST
    }

    //by default return original list
    return this.items
  }
},
data(){
  return {
    items: [
      {
        id: 1,
        title: 'Price: Low to High',
        sort: 1
      },
      {
        id: 2,
        title: 'Price: High to Low',
        sort: 2
      },
      {
        id: 3,
        title: 'Newest first',
        sort: 3
      },
      {
        id: 4,
        title: 'Oldest first',
        sort: 4
      }
    ],
    sort: null
  }
},
methods:{
  sortBy(){
    this.sort = !this.sort
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.