我正在使用VueRouter根据URL加载模板。当我尝试使用组件中app.data
中定义的属性时,会收到一个[VueWarn] Property or method "role" is not defined
。
如何将每个数据属性传递给子组件?
这是我的脚本:
const Home = { template: '<p>home page, {{role}}</p>' }
const NotFound = { template: '<p>Page not found</p>' }
const routes = [
{path: '/', component: Home}
{path: '*', component: NotFound}
]
Vue.use(VueRouter)
var app = new Vue({
el: '#app',
data: {
role: 0,
cookiesAlert: true
},
router: new VueRouter({routes})
})
最佳答案
我认为您的路由器构造选项设置不正确。通常,我更喜欢使用“命名路由”,因此我将设置为:
const router = new VueRouter({
routes: [
{ name: 'role', path: '/:role', component: User },
{ path: '*', component: Home }
]
})
而且,如果我不正确地理解您的问题,您想要做的是通过url将父组件中的“数据”传递给子组件,并读取子组件中的数据?
const User = {
template: '<div><br/>Role read from url is {{ $route.params.role }}</div>'
}
const Home = {
template: '<div><br/>Welcome</div>'
}
const router = new VueRouter({
routes: [
{ name: 'role', path: '/:role', component: User },
{ path: '*', component: Home }
]
})
new Vue({
router,
el: '#app',
data: {
role: 'default role'
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.2/vue-router.min.js"></script>
<div id="app">
The role is (Please change the 'role' value and click on '/User' link): <input v-model="role" type="text" /> <br/>
<router-link :to="{ name: 'role', params: { role: role }}">User</router-link>
<router-link to="/">Home</router-link>
<router-view></router-view>
</div>
或者,如果您不想使用
$route.params.role
,我将在路由器配置选项中将'props'设置为true。当props设置为true时,route.params将被设置为组件props。
const router = new VueRouter({
routes: [
{ name: 'role', path: '/:role', component: User, props: true },
{ path: '*', component: Home }
]
})
并绑定到子组件内部的“道具”。
const User = {
props: ['role'],
template: '<div><br/>Role read from url is {{ role }}</div>'
}
关于javascript - 如何将应用程序数据传递到VueRouter组件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53841413/