vue.jsvuejs3vue-composition-apivue-script-setup

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


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 class="my-3">
  <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.


Solution

  • 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>