2

How can I display the data from selected option, like in the example from docs vuejs.org but with component?

<div id="app">
  <selection></selection>
  <div v-if="post">
    selected post:
    {{post.title}}
  </div>
  <div v-else>
    no posts
  </div>
</div>

main.js

Vue.component('selection', {
  template: "<select v-model='post'><option v-for='post in posts' v-bind:value='post.val'>{{post.title}}<option></select>",
  data: function() {
    return {
      posts: [{ 
        title: "lorem ipsum 1", val: '1' }, {
        title: "lorem ipsum 2", val: '2' }, {
        title: "lorem ipsum 3", val: '3' }
      ],
      post: null
    }
  },
})
new Vue({
  el: "#app",
  data: {
  post: null
  }
}).$mount('#app')

fiddle

1
  • Why do you want to access selected post from parent. do it in the component itself. Commented Oct 10, 2016 at 4:14

1 Answer 1

3

You can make your component work with the v-model directive by implementing two features:

  • accept a value prop
  • emit an inputevent with the new value

First off, change your template to bind your select tag to the entire post object (not just the val property):

template: "<select v-model='post'><option v-for='post in posts' v-bind:value='post'>{{post.title}}<option></select>"

Declare your component to have a 'value' property:

props: ['value']

Now watch the component's post property and emit an input event with the selected post:

  watch: {
    post: function() {
        this.$emit('input', this.post);
    }
  }

Then you simply use the v-model directive on your custom component:

<selection v-model="post"></selection>

Here is a complete jsFiddle showing this in action.

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

1 Comment

Yes, exactly what I was looking for. Thanks for explanation.

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.