Home > Enterprise >  How do I show options in select using v-for with Vue3?
How do I show options in select using v-for with Vue3?

Time:09-27

The script part:

<script export>
    let categories=ref({})
    let selectedCategory

    onMounted(async () => {
        getCategories()
    })

    const getCategories=async () => {
        let response=await axios.get(`/api/get_all_category/`)
        categories=response.data.categories
        console.log(categories)
    }
</script>

The output of console.log(categories) is:

enter image description here

The template part:

<div >
  <p>Product type</p>
  <select v-model="selectedCategory">
    <option v-for="category in categories" :key="category.id" :value="category.id">
      {{ category.name }}
     </option>
   </select>
</div>

But no, checking the page the select has no options:

enter image description here

There are no other warnings or errors in the console.

CodePudding user response:

Replace export in <script export> by setup, and .value when you assign the respone to categories :

<script setup>
      let categories = ref([])
      let selectedCategory=ref([])
    
      onMounted(async () => {
        getCategories()
      })
    
      const getCategories = async () => {
        let response = await axios.get(`/api/get_all_category/`)
        categories.value = response.data.categories
        console.log(categories)
      }
    </script>
  • Related