使用 style 或 class 直接設置寬度
可以通過內聯樣式或 CSS 類來直接設置 el-input 的寬度為 100%,使其自適應父容器的寬度
<template><div style="width: 100%;"><el-input style="width: 100%;" v-model="input"></el-input></div>
</template>
或者使用 CSS 類
<template><div class="input-container"><el-input class="full-width-input" v-model="input"></el-input></div>
</template><style>
.input-container {width: 100%;
}.full-width-input {width: 100%;
}
</style>
使用 el-form-item 的 label-width 屬性
在 el-form 中使用 el-input,可以通過設置 el-form-item 的 label-width 來控制輸入框的寬度。如果 label-width 設置為 auto 或 0,輸入框會自動填充剩余空間.
<template><el-form :model="form" label-width="auto"><el-form-item label="用戶名"><el-input v-model="form.username"></el-input></el-form-item></el-form>
</template><script>
export default {data() {return {form: {username: ''}};}
};
</script>
使用 flex 布局
通過 flex 布局,可以讓 el-input 自動填充剩余空間。
<template><div style="display: flex;"><el-input style="flex: 1;" v-model="input"></el-input></div>
</template>
使用 el-col 和 el-row 進行柵格布局
在 el-row 和 el-col 中使用 el-input,可以通過設置 el-col 的 span 屬性來控制輸入框的寬度。
<template><el-row><el-col :span="24"><el-input v-model="input"></el-input></el-col></el-row>
</template>
或者根據需要調整 span 的值:
<template><el-row><el-col :span="12"><el-input v-model="input"></el-input></el-col></el-row>
</template>
使用 el-input 的 size 屬性
雖然 size 屬性主要用于控制輸入框的大小(medium、small、mini),但它不會直接影響寬度。可以結合其他方法來實現自適應。
<template><el-input size="small" style="width: 100%;" v-model="input"></el-input>
</template>
使用 el-input 的 resize 屬性(適用于 textarea)
如果使用的是 el-input 的 type=“textarea”,可以通過 resize 屬性來控制文本域的調整行為,但這與寬度自適應關系不大。
<template><el-input type="textarea" resize="none" v-model="textarea"></el-input>
</template>
使用 CSS calc() 函數
如果需要更精確的控制,可以使用 calc() 函數來動態計算寬度。
<template><div style="width: 100%;"><el-input style="width: calc(100% - 20px);" v-model="input"></el-input></div>
</template>
總結
最常用的方法是直接設置 el-input 的寬度為 100%,或者通過 flex 布局來實現自適應。如果在 el-form 中使用 el-input,可以通過 label-width 來控制輸入框的寬度。根據具體的布局需求,選擇合適的方法來實現寬度自適應。