You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js中select下拉框默认选中值设置问题求助

Fixing Vue.js Select Default Value Issue with v-model

Hey there! I see you're having trouble getting the default selected value to work with Vue's v-model on a select component. Let's break down what's going on and fix it step by step.

The Root Cause

When you use v-model with a select element in Vue, Vue takes full control of the selected state—it ignores the native selected="selected" attribute entirely. That's why your first approach had an empty default value, and the second worked but lost form binding functionality.

The Correct Solution

To make both the default selection and v-model binding work, you need to initialize the variable bound to v-model with the value of your default option. Here's how to adjust your code:

  1. Initialize the sort_brand variable in your component's data to "all" (matching the value of your "All(Brands)" option):
export default {
  data() {
    return {
      sort_brand: "all", // Set default value here
      brands: [] // Your brand data goes here
    };
  }
};
  1. Update your template (you can keep the v-model and remove the native selected attribute since it's no longer needed):
<select v-model="sort_brand" id="sort-brand" class="form-control">
  <option value="all">All(Brands)</option>
  <option v-for="brand in brands" :key="brand.id" :value="brand.id">{{ brand.name }}</option>
</select>

Note: I added :key="brand.id" to the v-for loop—this is a Vue best practice for list rendering to help Vue track elements efficiently.

Handling Dynamic Brand Data (If Applicable)

If your brands array is loaded asynchronously (e.g., from an API), make sure you set sort_brand to "all" after the data is fetched, or initialize it upfront (since "all" is a static option, initializing it in data() should still work even if brands loads later).

Why Your Original Approaches Didn't Work

  • First approach: The native selected attribute was ignored because v-model was overriding the select's state, and sort_brand wasn't initialized to match the default option's value.
  • Second approach: Without v-model, the native selected attribute works, but you lose Vue's reactive form binding—so you can't easily access or update the selected value in your component logic.

内容的提问来源于stack exchange,提问作者TechPotter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:38:03