Страницы Vue.js и OMDb с роутером - PullRequest
0 голосов
/ 07 ноября 2019

Я пытаюсь использовать bootstrap-vue pagination nav, чтобы при смене страницы на кнопке страницы это изменение передавалось в вызов 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>

Как мне изменить мой код, чтобы / route / moviename? Page = 2 и т. Д. Учитывались бы в вызове ajax, когда linkGen делаетновый URL в роутер? Я пробовал разные вещи, но вернул код обратно в исходную точку. Моя логика заключается в том, что наблюдатель должен быть модифицирован для прослушивания изменений страницы, но я новичок в Vue. : (

РЕДАКТИРОВАТЬ: Вот как я решил проблему

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

1 Ответ

0 голосов
/ 08 ноября 2019

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>
...