vue 2.0 路由设置问题

代码设置路由

这里组件 我建立了 两个 一个是Books.vue 一个是 Book.vue


这里 代码 created 我如果 只写 这些 只能获取到第一次 用户点击的id 所以不能这么写 我需要监控用户每次点击 连接 传递后的id
所以需要 些 $watch 监控顶级实例 this.$route.params 变化

代码
1 <template> 2 <div> 3 <p>id:{{ book.id }}</p> 4 <p>title:{{ book.title }}</p> 5 <p>price:{{ book.price }}</p> 6 </div> 7 </template> 8 <script> 9 export default { 10 data() { 11 return { 12 books: [ 13 { id: '1', title: '红楼梦', price: 11 }, 14 { id: '2', title: '西游记', price: 12 } 15 ], 16 book: { id: 0, title: '', price: 0 } 17 } 18 }, 19 created() { 20 // const id = this.$route.params.id 21 // console.log(id 22 // ) 23 // this.book = this.books.find(function (item) { 24 // return item.id === id 25 // }) 26 27 this.$watch( 28 () => this.$route.params, 29 (toParams) => { 30 this.book = this.books.find((item) => item.id === toParams.id); 31 }, 32 { 33 immediate: true 34 } 35 ) 36 } 37 } 38 </script> 39 <style lang="less" scoped></style>
测试结果 切换点击 书籍 没有问题

浙公网安备 33010602011771号