我目前有两个几乎完全相同的组件。 HTML 结构和 CSS 规则是相同的,唯一的区别是在这些组件的 mounted()
上,发出了不同的 GET 请求。一位获得所有访问过的地点,一位获得所有愿望 list 的地点。对两个 GET 请求的响应具有相同的结构,只是根据用户访问过的内容或愿望 list 返回不同的位置。
所以我的问题是,我是否打算将这 2 个组件合并为 1 个组件?如果我要这样做,我将如何确定是否需要对访问过的地点或愿望 list 地点发出 GET 请求?也许基于 URL?如果 URL 是 http://localhost:8080/#/Admin/visited
则执行 GET 请求,获取所有访问过的地点,如果是 http://localhost:8080/#/Admin/wishlist
获取心愿单地点?
此外,什么名称适合该组件,因为它将用于获取访问过的地点和愿望 list 中的地点?另外,将替换 wishlist
和 visited
的数据属性的合适名称是什么?
心愿单.vue
<template>
<div class='wishlisted-sights-list'>
<div @click='selectSight(index)' class='wishlisted-sight' v-if='wishlist != null' v-for='(wishlistedPlace, index) in wishlist'>
<img class='wishlisted-sight-photos' :src="'https://maps.googleapis.com/maps/api/place/photo?maxwidth=300&photoreference=' + wishlistedPlace.result.photos[0].photo_reference + '&key='">
<div class="">
<p class='wishlisted-sights-name'>{{ wishlistedPlace.result.name }}</p>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
data(){
return {
wishlist: null,
username: this.$route.params.username,
}
},
methods: {
selectSight(index) {
const placeId = this.wishlist[index].result.place_id;
this.$router.push('/' + this.username + '/' + placeId)
}
},
mounted() {
axios.get('/getWishlist/' + this.username)
.then(response => {
this.wishlist = response.data.wishlistedPlaces
}).catch((error) => console.log(error));
}
}
</script>
访问过的.vue
<template>
<div class='visited-sights-list'>
<div @click='selectSight(index)' class='visited-sight' v-if='visited != null' v-for='(visitedPlace, index) in visited'>
<img class='visited-sight-photos' :src="'https://maps.googleapis.com/maps/api/place/photo?maxwidth=300&photoreference=' + visitedPlace.result.photos[0].photo_reference + '&key='">
<div class="">
<p class='visited-sights-name'>{{ visitedPlace.result.name }}</p>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
data(){
return {
visited: null,
username: this.$route.params.username,
}
},
methods: {
selectSight(index) {
const placeId = this.visited[index].result.place_id;
this.$router.push('/' + this.username + '/' + placeId)
}
},
mounted() {
axios.get('/getVisited/' + this.username)
.then(response => {
this.visited = response.data.visitedPlaces
}).catch((error) => console.log(error));
}
}
</script>
最佳答案
将获取数据与显示数据分开。然后,父级可以在其 mounted/created
Hook 中执行这两个请求,并将它们作为 prop 传递给显示组件:
<places :places="visited"/>
<places :places="whishlist"/>
关于javascript - 2 个组件几乎完全相同。唯一的区别是每个组件都有不同的 GET 请求。合并他们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56208361/