Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

点击搜索按钮van-list请求了两次第一页

界面上有一个输入框和一个按钮,输入值之后点击搜索按钮,将列表清空从第一页开始请求。我如果不手动this.getList()的话,van-list不会自动请求。但是我手动请求后,van-list会请求两次第一页,我要怎么写才不会请求两次呢?

页面的搜索框如图(搜索框下面是列表):
image.png

<template>
  <div class="page">
    <div class="input-box">
      <img src="@/assets/searchMark.png" alt="" class="mark">
      <input type="text" class="input1" placeholder="输入关键词" v-model="search">
      <van-button type="info" @click="toSearch()">搜索</van-button>
    </div>
    <van-list
      v-model="loading"
      :finished="finished"
      :error.sync="error"
      error-text="请求失败,点击重新加载"
      finished-text="没有更多了"
      @load="getList"
    >
    </van-list>
  </div>
</template>

<script>
export default {
  data() {
    return {
      search: '',
      searchVal: '%',
      finished: false,
      currentPage: 1,
      list: [],
      province: '',
      type: '',
      level: '',
      error: false,
      loading: false,
      pageSize: 10,
    }
  },
  watch: {
    search: function(val) {
      if (!val) {
        this.searchVal = '%'
        this.currentPage = 1
        this.finished = false
        this.getList()
      }
    }
  },
  methods: {
    toSearch() {
      this.searchVal = this.search
      this.list.splice(0, this.list.length)
      this.currentPage = 1
      this.finished = false
      this.getList()
    },
    getList() {
      getSchoolList({
        universityName: this.searchVal,
        page: this.currentPage,
        pageSize: this.pageSize,
        province: this.province,
        type: this.type,
        level: this.level
      }).then(res => {
        this.loading = false
        if (res.code === 0) {
          if (this.currentPage == 1) {
            this.list.splice(0, this.list.length)
          }
          if (res.data.length < this.pageSize) {
            this.finished = true
          } else {
            this.currentPage += 1
          }
          this.list = this.list.concat(res.data)
        } else {
          console.log(res.msg)
        }
      }).catch(() => {
        this.loading = false
        this.error = true;
      })
    },
  }
}
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

解决了。应该是vant-list会监听finished的变化,如果在清空输入框前finished的值为true的话,再重新置为false,会自动请求一次,加上手动的一次,一共两次。如果一开始为false,则清空后不会自动请求。所以把watch的代码改成如下:

watch: {
    search: function(val) {
      if (!val) {
        this.searchVal = '%'
        this.currentPage = 1
        if (this.finished) {
          this.finished = false
        } else {
          this.getList()
        }
      }
    }
  },

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...