所以我多次在代码中看到过这个例子,并且我试图抓住看起来像重复获取函数的东西。我理解Navigation Guard的作用是拉取数据,以便在页面显示之前呈现它。但我不明白为什么调用fetchData
方法后立即执行同样的操作。或者我可能没有正确理解这段代码。我实际上运行了代码并注释掉了fetchData
方法,并没有看到任何差异。
<script>
import db from './firebaseInit'
export default {
name: 'view-contact',
data () {
return {
firstname: null,
lastname: null,
emailaddress: null,
phonenumber: null
}
},
beforeRouteEnter (to, from, next) {
db.collection('contacts').where('slug', '==', to.params.person).get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
next(vm => {
vm.firstname = doc.data().firstname
vm.lastname = doc.data().lastname
vm.emailaddress = doc.data().emailaddress
vm.phonenumber = doc.data().phonenumber
})
})
})
},
watch: {
'$route': 'fetchData'
},
methods: {
fetchData () {
db.collection('contacts').where('slug', '==', this.$route.params.person).get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(doc.id, ' => ', doc.data())
this.firstname = doc.data().firstname
this.lastname = doc.data().lastname
this.emailaddress = doc.data().emailaddress
this.phonenumber = doc.data().phonenumber
})
})
}
}
}
</script>