Skip to content

Commit 8b717a4

Browse files
committed
取得資料方法2
1 parent 6995135 commit 8b717a4

File tree

1 file changed

+21
-26
lines changed

1 file changed

+21
-26
lines changed

src/components/People.vue

Lines changed: 21 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -24,33 +24,28 @@ export default {
2424
error: null,
2525
}
2626
},
27-
created() {
28-
// watch 路由的參數,以便再次獲取數據
29-
this.$watch(
30-
() => this.$route.params,
31-
() => {
32-
this.fetchData()
33-
},
34-
// 組件創建完後獲取數據,
35-
// 此時 data 已經被 observed 了
36-
{ immediate: true }
37-
)
27+
beforeRouteEnter(to, from, next) {
28+
console.log('beforeRouteEnter')
29+
getUser(to.params.id, (err, User) => {
30+
next(vm => vm.setData(err, User))
31+
})
3832
},
39-
methods: {
40-
fetchData() {
41-
this.error = this.User = null
42-
this.loading = true
43-
// replace `getUser` with your data fetching util / API wrapper
44-
// 用你的數據獲取 util 或 API 替換 `getUser`
45-
getUser(this.$route.params.id, (err, User) => {
46-
this.loading = false
47-
if (err) {
48-
this.error = err.toString()
49-
} else {
50-
this.User = User
51-
}
52-
})
53-
},
33+
// 路由改變前,組件就已經渲染完了
34+
// 邏輯稍稍不同
35+
async beforeRouteUpdate(to, from) {
36+
console.log('beforeRouteUpdate')
37+
getUser(to.params.id, (err, User) => {
38+
this.setData(err,User)
39+
})
5440
},
41+
methods: {
42+
setData (err, User) {
43+
if (err) {
44+
this.error = err.toString()
45+
} else {
46+
this.User = User
47+
}
48+
}
49+
}
5550
}
5651
</script>

0 commit comments

Comments
 (0)