Vue + Element 文本域添加清空小叉号
<template>
<div>
<el-input v-model='inputValue' clearable @clear='clearInput'></el-input>
</div>
</template>
<script>
import { Input } from 'element-ui';
export default {
components: {
'el-input': Input,
},
data() {
return {
inputValue: '',
};
},
methods: {
clearInput() {
this.inputValue = '';
},
},
};
</script>
<h2>代码详解</h2>
<ol>
<li><strong>引入 Element UI 的 Input 组件和 CSS 样式:</strong></li>
</ol>
<pre><code class="language-html"><template>
<div>
<el-input v-model='inputValue' clearable></el-input>
</div>
</template>
<script>
import { Input } from 'element-ui';
export default {
components: {
'el-input': Input,
},
// ...
};
</script>
</code></pre>
<ol start="2">
<li><strong>使用 v-model 绑定文本域值和 <code>clearable</code> 属性:</strong></li>
</ol>
<p><code>v-model</code> 指令将文本域的值绑定到 <code>inputValue</code> 变量上,<code>clearable</code> 属性则会在文本域右侧显示一个小叉号。</p>
<ol start="3">
<li><strong>添加清空方法 <code>clearInput</code>:</strong></li>
</ol>
<pre><code class="language-html"><template>
<div>
<el-input v-model='inputValue' clearable @clear='clearInput'></el-input>
</div>
</template>
<script>
// ...
methods: {
clearInput() {
this.inputValue = '';
},
},
// ...
</script>
</code></pre>
<ol start="4">
<li><strong>使用 <code>@clear</code> 事件监听器:</strong></li>
</ol>
<p>当点击小叉号时,会触发 <code>clearInput</code> 方法,将 <code>inputValue</code> 设置为空字符串,从而清空文本域的内容。</p>
<h2>总结</h2>
<p>通过以上步骤,你就可以在 Vue 和 Element UI 的文本域中轻松添加一个清空小叉号功能。</p>
原文地址: https://www.cveoy.top/t/topic/qkIa 著作权归作者所有。请勿转载和采集!