Javascript 使用不同的路由但使用相同的组件VueJS 3获取数据
请检查此代码: 它基本上显示了两条路由,使用的是使用API内容的相同组件 Main.jsJavascript 使用不同的路由但使用相同的组件VueJS 3获取数据,javascript,vue.js,vue-router,vuejs3,Javascript,Vue.js,Vue Router,Vuejs3,请检查此代码: 它基本上显示了两条路由,使用的是使用API内容的相同组件 Main.js const router = createRouter({ history: createWebHistory(), routes: [ { path: "/route1", name: "Route1", component: BaseContent,
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: "/route1",
name: "Route1",
component: BaseContent,
meta: {
title: 'Route 1'
}
},
{
path: "/route2",
name: "Route2",
component: BaseContent,
meta: {
title: 'Route2'
}
}
]
});
BaseContent.vue
<base-section v-for="entry in this.entries" :key="entry" lang="lang-markup" :title="entry.title">
<template v-slot:content>
<div v-html="entry.content"></div>
</template>
<template v-slot:examples>
<div v-html="entry.examples"></div>
</template>
<template v-slot:code>
{{entry.code}}
</template>
</base-section>
</template>
<script>
export default {
mounted(){
this.$nextTick(function () {
Prism.highlightAll();
this.getData()
})
},
updated(){
this.$nextTick(function () {
Prism.highlightAll();
this.getData()
})
},
methods:{
getData(){
const url= 'https://example.dev/api/collections/get/'+this.$route.name+'?token=XXXXXXXXX'
fetch(url)
.then(collection => collection.json())
.then(collection => {
const entries = [];
for (const id in collection.entries) {
entries.push({
title: collection.entries[id].Title,
content: collection.entries[id].Content,
examples: collection.entries[id].Examples,
code: collection.entries[id].Code,
});
}
this.entries = entries;
});
}
},
data() {
return {
entries:[]
};
},
};
</script>
{{entry.code}
导出默认值{
安装的(){
此.$nextTick(函数(){
Prism.highlightAll();
这个文件名为getData()
})
},
更新的(){
此.$nextTick(函数(){
Prism.highlightAll();
这个文件名为getData()
})
},
方法:{
getData(){
常量url=https://example.dev/api/collections/get/“+此.$route.name+”?令牌=XXXXXXXXX”
获取(url)
.then(collection=>collection.json())
。然后(收集=>{
常量条目=[];
for(collection.entries中的常量id){
推送({
标题:集合。条目[id]。标题,
内容:集合。条目[id]。内容,
示例:集合。条目[id]。示例,
代码:集合。条目[id]。代码,
});
}
this.entries=条目;
});
}
},
数据(){
返回{
条目:[]
};
},
};
问题:
这个解决方案有效。但有两件事让我抓狂。
1st-内容的行为方式很奇怪,当我单击链接以遵循其中任何一条路线时,内容在两条路线内容之间闪烁,然后才实际呈现正确的内容
2nn-如果我打开开发工具,我会看到内容在不断更新(开发工具的代码选项卡上的节标记一直闪烁紫色,表示更新)
关于我做错了什么有什么提示吗
PS:我是VUE JS的新手
非常感谢
问候,,
我设法解决了这个问题。 经过一番挖掘,我发现我所需要的只是为我的
App.vue
文件中的
组件提供一个唯一的:key
标识符
所以我刚才加了一句:
它解决了这个问题,因为Vue的反应系统知道它需要重新加载整个组件,因为密钥是唯一的,而在它不是唯一的之前
希望能在这方面帮助别人
问候,,
T