Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

111
Visualizações
Set default value to option select menu with Vue3

I get all the categories:

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

categories.value looks like this:

enter image description here

I set the default option:

let selectedCategory
const getSingleProduct = async () => {
  let response = await axios.get(`/api/get_edit_product/${props.id}`)
  form.value = response.data.product
   
  //form.value.category_id is a number from 1 to 6
  selectedCategory = ref(form.value.category_id) 
}

I build the select tag:

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

I can see all the options correctly but the default option is not set accordingly.

almost 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Try first to define selectedCategory as reactive with ref:

const { ref, computed } = Vue
const app = Vue.createApp({
  setup() {
    const categories = ref([{id: 1, name: 'aaa'}, {id: 2, name: 'bbb'}, {id: 3, name: 'ccc'}])
    let selectedCategory = ref(null)
    const getSingleProduct = () => {
      //let response = await axios.get(`/api/get_edit_product/${props.id}`)
     // form.value = response.data.product
      //form.value.category_id is a number from 1 to 6
       selectedCategory.value = 3
    }
    getSingleProduct()
    return { categories, selectedCategory }
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div class="my-3">
    <p>Product type</p>
    <select v-model="selectedCategory">
      <option v-for="category in categories" :key="category.id" :value="category.id" :selected="selectedCategory">
        {{ category.name }}
      </option>
    </select>
  </div>
</div>

almost 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda