vuejs 获取input
时间: 2023-09-13 07:10:13 浏览: 39
你可以通过 `v-model` 指令获取 input 元素的值,例如:
```html
<template>
<div>
<input v-model="message" type="text">
<button @click="sendMessage">发送</button>
</div>
</template>
<script>
export default {
data() {
return {
message: ''
}
},
methods: {
sendMessage() {
console.log(this.message);
// 在这里可以使用 this.message 获取 input 元素的值
}
}
}
</script>
```
在上面的代码中,我们通过 `v-model` 将 input 元素绑定到 `message` 数据属性上,然后在 `sendMessage` 方法中使用 `this.message` 获取 input 元素的值。
相关问题
vuejs 动态添加input框 具体代码
可以使用Vue的v-for指令和数组来实现动态添加input框。具体代码如下:
HTML部分:
```
<div id="app">
<div v-for="(input, index) in inputs" :key="index">
<input type="text" v-model="input.value">
<button @click="removeInput(index)">删除</button>
</div>
<button @click="addInput">添加</button>
</div>
```
JavaScript部分:
```
new Vue({
el: '#app',
data: {
inputs: [{ value: '' }]
},
methods: {
addInput() {
this.inputs.push({ value: '' });
},
removeInput(index) {
this.inputs.splice(index, 1);
}
}
});
```
这样就可以实现动态添加和删除input框了。
写一个 vuejs 动态生成input框的组件
A:
下面是一个基本的 vuejs 组件,它可以动态生成输入框:
```html
<template>
<div>
<button @click="addInput">Add Input</button>
<div v-for="(input, index) in inputs" :key="index">
<input :name="input.name" :placeholder="input.placeholder">
<button @click="removeInput(index)">Remove Input</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
inputs: [
{ name: "input1", placeholder: "Input 1" },
{ name: "input2", placeholder: "Input 2" }
]
};
},
methods: {
addInput() {
this.inputs.push({
name: `input${this.inputs.length + 1}`,
placeholder: `Input ${this.inputs.length + 1}`
});
},
removeInput(index) {
this.inputs.splice(index, 1);
}
}
};
</script>
```
在这个组件中,我们使用一个按钮来添加新的输入框,使用 `v-for` 指令循环渲染所有的输入框。我们可以使用 `v-model` 指令来绑定输入框的内容。在 `addInput` 方法中,我们使用 `push` 方法向 `inputs` 数组添加新的输入框对象,同时为每个新输入框分配一个唯一的名称和占位符。`removeInput` 方法可以删除指定位置的输入框。