search

Home  >  Q&A  >  body text

ComboBox template component using VueJS

<p>我想使用 <code>vuejs v3</code> 制作一个 <strong>Combobox</strong> 模板组件,为此我有以下代码:</p> <pre class="brush:html;toolbar:false;"><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> </pre> <p>但是我使用 <code>v-for</code> 的方式对我来说似乎不正确,你能告诉我如何纠正吗?提前致谢。</p>
P粉550323338P粉550323338448 days ago467

reply all(1)I'll reply

  • P粉616111038

    P粉6161110382023-09-04 16:19:58

    I see a lot of stuff, to answer your question clearly, v-for is used on elements.

    <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 cannot define props and data with the same name. Props, inject properties and values ​​into the data. Exactly the same, but the data comes from the parent and you pass values ​​from the parent to the child.

    So if you need to pass data, use props, but don't define it inside the data.

    There is a working example of all of this (I'm using data instead of props to improve readability). < /p>

    reply
    0
  • Cancelreply