0

我正在尝试使用 bootstrap-vue 分页导航,这样当我更改页面按钮上的页面时,该更改将根据请求的页面传递给 ajax 调用。

我的路由器:

export default new Router({
  routes: [
    {
      path: '/route/:moviename/',
      name: 'myComponent',
      props: true,
      component: myComponent
    }
  ]
})

还有我的 Vue 组件:

// This is my nav-bar

<template>
     <div>
        <b-pagination-nav
          :link-gen='linkGen'
          :number-of-pages='pages'
          use-router
        ></b-pagination-nav>
    </div>
</template>

<script>
export default {
  props: ['moviename'],
  data () {
    return {
      res: '',
      pages: 1,
    }
  },
  methods: {
    myFunction (value) {
      // added &page=1 to the url to illustrate where it should be
      fetch('https://www.omdbapi.com/?s=' + value + ' &page=1 &apikey')
        .then(res => {
          return res.json()
        })
        .then(res => {
            this.res = res
            this.pages = Math.ceil(res.totalResults / 10)
          }
        })
    },
    // adds new path to router (route/moviename?page=pageNum)
    linkGen (pageNum) {
      return pageNum === 1 ? '?' : `?page=${pageNum}`
    }
  },
  mounted () {
    this.myFunction(this.moviename)
  },
  watch: {
    moviename (value) {
      this.myFunction(value)
    }
  }
}
</script>

如何修改我的代码,当 linkGen 在路由器中创建新的 url 时,/route/moviename?page=2 等将在 ajax 调用中计入?我尝试了不同的方法,但将代码恢复到了我的起点。我的逻辑是应该修改观察者来监听页面变化,但我是 Vue 的新手。:(

编辑:这是我解决问题的方法

linkGen (pageNum) {
      return pageNum === 1 ? `/route/${this.$store.state.title}` : `/route/${this.$store.state.title}&page=${pageNum}`
    }
4

1 回答 1

1

myComponent$route应该检查当前查询对象中的页码:

<!-- myComponent template -->
<template>
  <div>
    <p>Movie: {{ $route.params.moviename }}</p>
    <p>Page Number: {{ pageNum }}</p>
    <p>Result: {{ result }}</p>
  </div>
</template>

<script>
export default {
  name: 'myComponent',
  data() {
    // Response from AJAX query stored here
    result: ''
  },
  computed: {
    pageNum() {
      // Fallback to page 1 if no page query parameter in the current route
      return this.$route.query.page || '1'
    }
  },
  watch: {
    pageNum: {
      // Use an immediate watcher so that AJAX request made on created
      immediate: true,
      handler(newPage, oldPage) {
        // perform AJAX query here
        // Just some example code you would need to modify
        // based on you API calls and needs
        this.$axios.get('/some/url/here/' this.$route.params.moviename + '/' + newPage)
          .then(response => {
             this.result = response.data
          })
          .catch(() => {
            this.result = 'Error'
          })
      }
    }
  }
}
</script>
于 2019-11-07T21:55:43.643 回答