vue2.0使用watch实现一个表单的查询
时间: 2024-05-01 15:22:57 浏览: 9
假设我们有一个表单,包含两个输入框,分别是关键词和类型,我们可以使用 `watch` 监听这两个输入框的变化,并在变化时触发查询操作。
首先,我们需要在 `data` 中定义这两个变量:
```javascript
data() {
return {
keyword: '',
type: ''
}
}
```
然后,我们可以使用 `watch` 监听这两个变量的变化:
```javascript
watch: {
keyword: function(newVal, oldVal) {
this.query()
},
type: function(newVal, oldVal) {
this.query()
}
},
```
在每个 `watch` 的回调函数中,我们调用 `query` 方法来执行查询操作。在 `query` 方法中,我们可以获取当前的关键词和类型,然后执行查询逻辑:
```javascript
methods: {
query() {
const keyword = this.keyword
const type = this.type
// 执行查询逻辑
// ...
}
}
```
最后,我们需要在模板中绑定输入框的值,并给查询按钮添加点击事件:
```html
<template>
<div>
<input v-model="keyword" />
<input v-model="type" />
<button @click="query">查询</button>
</div>
</template>
```
完整代码如下:
```html
<template>
<div>
<input v-model="keyword" />
<input v-model="type" />
<button @click="query">查询</button>
</div>
</template>
<script>
export default {
data() {
return {
keyword: '',
type: ''
}
},
watch: {
keyword: function(newVal, oldVal) {
this.query()
},
type: function(newVal, oldVal) {
this.query()
}
},
methods: {
query() {
const keyword = this.keyword
const type = this.type
// 执行查询逻辑
// ...
}
}
}
</script>
```