如何使用 vue.js 在下拉列表中获取选定值?

I have parent component vue like this :

<template>
    <form>
        <div class="row">
            <div class="col-md-4">
                <form-select id="color" name="color" :data="color">Color</form-select>
            </div>
            <div class="col-md-4">
                <form-select id="size" name="size" :data="size">Size</form-select>
            </div>
        </div>
        ...
        <a href="javascript:" class="btn btn-danger" @click="add">
            Add
        </a>
    </form>
</template>

<script>
    import FormSelect from '../form/FormSelect.vue'
    export default {
        data(){
            return {
                quantity: [
                    {id: 1, value: '1'},
                    {id: 2, value: '2'},
                    {id: 3, value: '3'}
                ],
                size: [
                    {id: 1, value: 'S'},
                    {id: 2, value: 'M'},
                    {id: 3, value: 'L'}
                ]
            }
        },
        components: {FormSelect},
        methods: {
            add(event) {
                const color = document.getElementById('color').value,
                      size = document.getElementById('size').value
            }
        }
    }
</script>

I have child component vue like this :

<template>
    <div class="form-group">
        <label :for="id" class="control-label"></label>
        <select :id="id" :name="name" class="form-control" v-model="selected">
            <option v-for="item in data">{{item.value}}</option>
        </select>
    </div>
</template>

<script>
    export default {
        props: ['id', 'name', 'data'],
        data(){
            return {
                selected: ''
            }
        }
    }
</script>

If I click add button, I success get values selected. But it still using javascript (document.getElementById)

I want to change it. So I want to using data binding vue component. But i'm still confused to use it

How can I do it with data binding?

解决方案

You need to emit the event from child component to send your data and use the on method to get that data in the parent component:

Parent:

<form-select id="color" name="color" :data="color" v-on:triggerChange="changeColor">Color</form-select>

methods: {
 // ...
 changeColor(selected) {
   // do what you want to do with selected
 }
 // ...
}

Child:

<select :id="id" :name="name" class="form-control" v-model="selected" v-on:change="applyColor">

methods: {
 // ...
 applyColor() {
   this.$emit('triggerChange',this.selected);
 }
 // ...
}


As per your comment, you can do like this:

this.$parent.$options.methods.someParentMethod(data)

Note:

Use $parent and $children sparingly - they mostly serve as an escape-hatch. Prefer using props and events for parent-child communication.

相关文章