1

I have prop "cat"

props: ['cat1'],

Ant this piece of code

<select class="form-control" @change="set_category">
   <option value="" disabled>Please select category</option>

   <option v-for="category in categories"
          :value="category" 
          :selected="cat1 == category.url">{{ category.name}}
   </option>
</select>

So this code is called when page its loading and the problem is, that after loading the page option changes but it doesn't triggers @change event, ant because of it i can't actually track which option was selected on page load. I tried alot versions with v-model ant etc but it sees i just stuck on it..

4
  • So you want to change cat1 when the user selects an option? Commented Sep 24, 2017 at 3:07
  • Can you show the set_category method please? Commented Sep 24, 2017 at 3:25
  • @RichardMatsen set_category method for the moment have only console.log('test') for debuging What i want to do, when page loads this code its called in the prop cat1 i have part of the url and in the :value="category" i actually have whole object... because cat1 comes from back-end i actually wanna to check if they equal to each other, I mean url from category object (category.url) and url from the prop "cat1". And it they are.. then i want to bind it via set_category method or using any other approach... Commented Sep 24, 2017 at 3:39
  • Sorry no luck. The only option I can see is to bind select to cat1 with v-model, then set a watch on cat1 that calls set_category. Commented Sep 24, 2017 at 6:15

2 Answers 2

1

Richard Matsen's answer is great. But if you only want to track value on page load, why not just call it on created (or mounted).

created() {
  this.set_category();
}

Here is a jsfiddle:

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

Comments

0

Here's a directive that will emit the change event as required

Vue.directive('binding-change', {
  update: function (el, binding, vnode) {
    const model = vnode.data.directives.find(d => d.name === 'model')
    if (model) {
      binding.value(model.value)
    }
  }
})

Use it like this

<select class="form-control" v-binding-change="set_category" v-model="cat1">
   <option value="" disabled>Please select category</option>
   <option v-for="(category, index) in categories"
      :key="index"
      :value="category" 
   </option>
</select>

methods: {
  set_category (newValue) {
  }
}

I haven't tried it with a prop (just a local variable), but I can say it emits the change event when the bound variable is changed in the background (unlike @change).

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.