Suppose I have a Vue.js component like this:
var Bar = Vue.extend({
props: ['my-props'],
template: '<p>This is bar!</p>'
});
And I want to use it when some route in vue-router is matched like this:
router.map({
'/bar': {
component: Bar
}
});
Normally in order to pass 'myProps' to the component I would do something like this:
Vue.component('my-bar', Bar);
and in the html:
<my-bar my-props="hello!"></my-bar>
In this case, the router is drawing automatically the component in the router-view element when the route is matched.
My question is, in this case, how can I pass the the props to the component?
<router-view :some-value-to-pass="localValue"></router-view>
and in your components just add prop:
props: {
someValueToPass: String
},
vue-router will match prop in component
sadly non of the prev solutions actually answers the question so here is a one from quora
basically the part that docs doesn't explain well is
When props is set to true, the route.params will be set as the component props.
so what you actually need when sending the prop through the route is to assign it to the params key ex
this.$router.push({
name: 'Home',
params: {
theme: 'dark'
}
})
so the full example would be
// component
const User = {
props: ['test'],
template: '<div>User {{ test }}</div>'
}
// router
new VueRouter({
routes: [
{
path: '/user',
component: User,
name: 'user',
props: true
}
]
})
// usage
this.$router.push({
name: 'user',
params: {
test: 'hello there' // or anything you want
}
})
In the router,
const router = new VueRouter({
routes: [
{ path: 'YOUR__PATH', component: Bar, props: { authorName: 'Robert' } }
]
})
And inside the <Bar /> component,
var Bar = Vue.extend({
props: ['authorName'],
template: '<p>Hey, {{ authorName }}</p>'
});
This question is old, so I'm not sure if Function mode existed at the time the question was asked, but it can be used to pass only the correct props. It is only called on route changes, but all the Vue reactivity rules apply with whatever you pass if it is reactive data already.
// Router config:
components: {
default: Component0,
named1: Component1
},
props: {
default: (route) => {
// <router-view :prop1="$store.importantCollection"/>
return {
prop1: store.importantCollection
}
},
named1: function(route) {
// <router-view :anotherProp="$store.otherData"/>
return {
anotherProp: store.otherData
}
},
}
Note that this only works if your prop function is scoped so it can see the data you want to pass. The route argument provides no references to the Vue instance, Vuex, or VueRouter. Also, the named1 example demonstrates that this is not bound to any instance either. This appears to be by design, so the state is only defined by the URL. Because of these issues, it could be better to use named views that receive the correct props in the markup and let the router toggle them.
// Router config:
components:
{
default: Component0,
named1: Component1
}
<!-- Markup -->
<router-view name="default" :prop1="$store.importantCollection"/>
<router-view name="named1" :anotherProp="$store.otherData"/>
With this approach, your markup declares the intent of which views are possible and sets them up, but the router decides which ones to activate.
const User = {
props: ['id'],
template: '<div>User {{ id }}</div>'
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User, props: true }
// for routes with named views, you have to define the props option for each named view:
{
path: '/user/:id',
components: { default: User, sidebar: Sidebar },
props: { default: true, sidebar: false }
}
]
})
Object mode
const router = new VueRouter({
routes: [
{ path: '/promotion/from-newsletter', component: Promotion, props: { newsletterPopup: false } }
]
})
That is the official answer.
link
Use:
this.$route.MY_PROP
to get a route prop
Related
I want to navigate to a specific tab in a page, with
this.$router.push({
name: "AdminNotifications",
params: { tab: "requests" },
})
so inside the page i can get the param and set the tab:
mounted() {
const routeTab = this.$route.params.tab;
if (routeTab) this.tab = routeTab;
}
It works if the current page is not AdminNotifications.
But else, there is an error:
NavigationDuplicated: Avoided redundant navigation to current
So... is there a way to just set the tab props, without navigate?
thanks
You can't navigate to a route if you're already there. But, since you're already there, you can just set this.tab to the desired value:
if (this.$route.name === 'AdminNotifications') {
this.tab = 'requests';
} else {
this.$router.push({
name: "AdminNotifications",
params: { tab: "requests" },
})
}
If the component in charge of navigating is not the same as the one containing tab, you could push the tab param to the $route:
if (this.$route.name === 'AdminNotifications') {
this.$router.replace({
params: { tab: "requests" }
});
} else {
this.$router.push({
name: "AdminNotifications",
params: { tab: "requests" },
})
}
And in the page component, replace the "watcher" in mounted with a proper watch, which sets tab to any truthy value of $route.params.tab, dynamically:
watch: {
'$route.params.tab': {
handler(val) {
if (val) {
this.tab = val;
}
},
immediate: true
}
}
If i understood your question correctly you can just do this.$route.params.tab = "any value" like any other variable. this.$route.params.tab is just a variable like all the others.
Here is how I was handling this with the vue-router.
Add one parent component which will contain tabs and a tab content components.
Your structure can looke like this:
tabs/Tab1.vue
tabs/Tab2.vue
tabs/Tab2.vue
Tab.vue
In Tabs.vue paste code below. The component should contain in the place where you want to display the content of your tabs and router-links to link a specific tab.
Tab.vue
<template>
<div class="tabs">
<router-link to="/tab1">Tab 1</router-link>
<router-link to="/tab2">Tab 2</router-link>
<router-link to="/tab3">Tab 3</router-link>
<router-view />
</div>
</template>
<script>
export default {
name: "tabs",
components: {},
};
</script>
Then fill tabs content components.
In your router.js register your tab routes as shown below.
import Tabs from "./Tabs";
import Tab1 from "./tabs/Tab1";
import Tab2 from "./tabs/Tab2";
import Tab3 from "./tabs/Tab3";
{
path: "/",
redirect: "/tab1",
component: Tabs,
children: [
{
path: "/tab1",
name: "tab1",
component: Tab1
},
{
path: "/tab2",
name: "tab2",
component: Tab2
},
{
path: "/tab3",
name: "tab3",
component: Tab3
}
]
}
Now you should be able to navigate a specific tab by router link.
In the file where you define the routes, you need to define the props for each route, something like this:
const routes = [
{
path: "admin-notifications",
name: "AdminNotifications",
component: AdminNotificationsView,
props: r => ({
tab: r.params.tab
})
}
]
And then define the prop tab in AdminNotificationsView assuming that's the component you use to render the view.
how can I mix Boolean and Object Mode in my Vue Router?:
props: true
with
props: { someRouteSpecificProps: "someValue"}
I need to also send props via router.push.
So:
//router
{
path: "somePath",
name: "someName",
props: { someRouteSpecificProps: "someSpecificValue" },
component: successAndLogoutPage,
},
//component
this.$router.push({
name: "someName",
query: this.$route.query,
params: {
ValueOnlyKnownInCompoent: 500000,
AnotherValueOnlyKnownInCompoent: "foo",
}
},
Using Vue 2, Js not ts.
Doing as I did, will ignore the props from the component. Doing props: true will use the props from the component but I still neet the someRouteSpecificProps directly in the router definition.
The solution is using the function mode:
props: (route) => {
return { someSpecificProps: 'value here', ...route.params };
},
In route the params are provided and can be provided to the props.
(Credit to #PerpetualWar from the vue discord, on whos advice the solution was formed)
I need to download files from remote api by vue-router link. Remote api returns files in base64.
I add route:
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '/files/:id', name: 'file', component: Vue.component('vue-file'), props: true }
],
});
and add component for it:
<template>
<div>
</div>
</template>
<script>
export default {
name: 'file',
props: {
id: String
},
mounted: function() {
this.download();
},
methods: {
download: function() {
let $this = this;
axios
.get('apiurl' + encodeURIComponent(this.id))
.then(function (response) {
download(response.data.base64content)
});
}
}
}
</script>
It works but I don't want to show component template <template><div></div></template>. I even don't want to refresh the content on the screen. Is it possible?
You shouldn't. Vue Components were done for rendering. Your implementation would be nicer as a mixin or plugin, if you don't want to render anything.
Although, I think you can do something like:
render() {
return null;
},
Using vue-router in a single page application with the code below, the watch $route function in not firing when redirecting to mycomponent.
Also the beforeRouteUpdate in mycomponent is also not firing.
How can I detect when a variable has been tagged on to a route during component load?
App.vue
<template>
<router-view></router-view>
</template>
<script>
import Vue from 'vue'
export default {
name: 'app'
}
</script>
index.js
import Vue from 'vue'
import Router from 'vue-router'
import MyView from '#/views/MyView'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
redirect: '/home',
name: 'Home',
children: [
{
path: '/mycomponent',
name: 'MyComponent',
component: MyComponentView
},
{
path: '/mycomponent/:id',
component: MyComponentView,
props: true
}
]}]})
mycomponent.vue
<template>
<component :is="activeComponent" :id="id"></component>
</template>
<script>
export default {
name: 'MyComponentView',
components: {
...
},
mounted: function() {
#this logs path in browser
console.log('>>mounted route: ' + this.$route.path)
},
watch: {
'$route': function () {
#this does not fire
console.log('route watcher: ' + this.$route.path)
}
},
beforeRouteUpdate (to, from, next) {
#this does not fire
console.log('>>beforeRouteUpdate')
},
data () {
return {
activeComponent: 'somecomponent'
}
}
}
</script>
component1.vue
...
mounted: function() {
Event.$on('vue-tables.row-click', function(data) {
#this logs correct information in browser
console.log('data.row.id: ' + data.row.id)
router.push({path: 'mycomponent', query: {id: data.row.id}})
})
},
...
It doesn't work because beforeRouteUpdate is in component which is going to reload (Look at Life cycle of Vue). When you change the route, watch & beforeRouteUpdate is terminated and you won't see any results. In this scenario you should provide something like this:
MainRouterView.vue
<template>
<router-view/>
</template>
<script>
name: 'MainRouterView',
beforeRouteUpdate (to, from, next) {
console.log('beforeRouteUpdate')
},
</script>
router.js
export default new Router({
routes: [
{
{
path: '/mycomponent',
name: 'MainRouterView',
component: MainRouterView,
children: [
{
path: '/mycomponent/:id',
component: SecondComponent,
}
]
},
}]})
But if you want to stick up with your structure and check the status of the current route, you can replace beforeRouteUpdate to beforeRouteEnter or beforeRouteLeave in the component. You can use global guard beforeEach in router as well.
To better understand how beforeRouteUpdate works, check out this snippet: http://jsfiddle.net/yraqs4cb/
I thought this would work:
{ path: '/course/:id', component: Course.extend({
props: { course: params.id }
}) },
Sadly, it's not that simple (it's not id either). How do I do this? (I just took a course on vue, can't believe I can't remember this)
As it is in the docs, you have to make props option true in the routes, see below code to understand it:
const User = {
props: ['id'],
template: '<div>User {{ id }}</div>'
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User, props: true }
]
})