Home > Blockchain >  ComboBox template component with VueJS
ComboBox template component with VueJS

Time:10-28

I want to make a Combobox template Component with vuejs v3 and to do so I have the following code:

<template>
    <select name={{selector_name}} class= "combobox" id={{selector_id}}>
        v-for=opt in {{selector_options}} 
        <option value=opt>
            opt
        </option>
    </select>
</template>

<script>
export default {
    name: 'ComboBox',
    data() {
        return {
            selector_name: null,
            selector_id: null,
            selector_options : null,
        }
    },
    props: {
        selector_name: {
            type: String,
            required: true
        },
        selector_id: {
            type: String,
            default: "combobox"
        },
        selector_options: {
            type: Array,
            required: true
        }
    },
    methods: {
        onChange: (event) => {
            console.log(event.target.value);
        },
    },
    computed: {},
}
</script>

But the way that I use v-for does not seem to be correct to me, can you please tell me how can I correct that? thanks in advance.

CodePudding user response:

I see a lot of things, to be clear and answer your questions, v-for is used on a element.

<template>
    // For mor readability i recommend you do bind your property:
    //  - name={{selector_name}} become :name="selector_name"
    <select :name="selector_name" class= "combobox" :id="selector_id">
        <!-- v-for is required with a unique key, you can take the index and use it -->
        <option v-for="(opt, index) in selector_options" :key="`opt ${index}`" value=opt>
           {{ opt }}
        </option>
    </select>
</template>

You can't define a props and data with the same name. Props, inject inside a data the property and value. It's exactly the same, but the data come from a parent where you pass a value to the child.

So use props if you need to pass data, but not define it too inside data.

There is a work example of all of that (i use data and not props for readability).

  • Related