我对Vue相当陌生,并且正在努力寻找合适的东西。不完全确定这是否可行,但我会问,我们会看到Stack Overflow神必须召唤出来。
我想知道是否可以在默认导出的data()部分内存储大量ID的组件数据/道具。
所以{{$ route.params.id}}设法从url的末尾捕获id,但是我想知道我是否可以让View返回存储在组件中某处的其他数据。所以基本上我可以在Project.Vue文件中存储数据,让我们说5个不同的ID,或者我只需要制作5个不同的文件(Project1.Vue,Project2.Vue等),然后将它们全部设置好作为单独的路线?
到目前为止,我已经尝试将添加位添加到data()元素,例如
data () {
return {
msg: 'Projects',
id: [{ 1: 'hi'}, {2: 'hey'}],
two: 'project two',
three: 'project three',
}
}
然后在<template>
内引用id,但这不起作用,因为它只返回整个对象。我也尝试过这里提到的脱钩:https://router.vuejs.org/en/essentials/passing-props.html但对此也没有喜悦。
对我糟糕的解释道歉但我希望有人可以帮助阐明这是否可行。使用的代码如下:
index.js
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home'
import Contact from '@/components/Contact'
import About from '@/components/About'
import Projects from '@/components/Projects'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/contact',
name: 'Contact',
component: Contact
},
{
path: '/about',
name: 'About',
component: About
},
{
path: '/projects',
name: 'Projects',
component: Projects
},
{
path: '/projects/:id',
name: 'Projects',
component: Projects,
props: {default: true}
},
]
})
Projects.Vue
<template>
<div id="projects">
<h1>{{ header }} {{ $route.params.id }}</h1>
{{id}}
</div>
</template>
<script>
export default {
name: 'Projects',
watch: {
'$route'(to, from) {
// react to route changes...
}
},
data () {
return {
header: 'Projects',
}
}
}
</script>
<style scoped>
</style>
答案 0 :(得分:0)
我已经设法解决了。
为了根据传入url的id动态传递数据,你需要创建一个数据对象,然后在<template>
的内部,你可以传入你创建的对象,然后传递方括号内的$ route.params.id。但是,值得注意的是,因为在data()内部创建的对象将使用零索引,所以值得在模板内添加-1。请参阅以下代码以了解它是如何工作的:
<template>
<div id="projects">
<h1>{{ msg }} {{ projects[$route.params.id - 1] }}</h1>
</div>
</template>
<script>
export default {
name: 'Projects',
watch: {
'$route'(to, from) {
// react to route changes...
}
},
data () {
return {
projects: [
{ id: 1,
name: 'Project numero uno'
},
{ id: 2,
name: 'Project secundo'
},
{ id: 3,
name: 'Project three'
},
]
}
}
}
</script>
<style scoped>
</style>