Search code examples
vue.jsselected

Dynamic default selected option


I have component to edit a product, in the select element i want to make the product category option as the default option, if that product category name is equal to the name in the category array being looped, then i want that option to be selected by default, but it's not working as expected.

const props = defineProps({
 product: Object, 
 categories: Object 
});

const form = useForm({
    category: "",
});



<select v-model="form.category">
 <option v-for="category in categories"
 :selected="category.name == product.category">
   {{ category.name }}
  </option>
</select>


Solution

  • export default {
      props: {
        product: Object,
        categories: Array,
      },
      setup(props) {
        const form = ref({
          category: props.product.category || '', // Set the default value based on product.category
        });
    
        return { form };
      },
    };