[英]Vue.js and OMDb pages with router
我正在尝试使用 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}`
}
myComponent
应该检查当前$route
查询 object 中的页码:
<!-- 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>
好吧,linkGen function 将?page=2(取决于 pageNum)添加到我的 url 的末尾,例如 /route/titanic?page=2
正确的方法是 /route/titanic&page=2 并且页面路由有效
有没有办法“?” 可以在linkGen function中用“&”替换吗? 当我手动切换“?” 到“&”,它将 /route/titanic?page=2 替换为 /route/&page=2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.