How to route to specific div in a component in vuejs 2 - javascript

My routes for the application are
const router = new VueRouter({
mode:'history',
routes:[
{
path:'/home',
name:'home',
component: Home
},
{
path: '/services',
name: 'services',
component: Services
},
{
path:'/blogs',
name:'blogs',
component:Blogs
},
{
path:'/pingme',
name:'pingme',
component:Pingme
}
],
})
Now, in services route I want to navigate to the which is present in the Home component. How can I create router so as to navigate to the services div when the services link is clicked?

Let's say you want to bring in focus to a specific div in the Service component.
we will make use of query params to achive this. You add add a dedicated url as well which will do this.
This is my route:
{
path: '/services',
name: 'services',
component: Services
}
Then in the url localhost:8000/services?show=mydiv and in the mounted hook of the component do something like this:
mounted() {
// add a id to the div we want to bring in foucs
// and id and the id is paased the query params
document.getElementById(this.$route.query.show).scrollIntoView()
}
Let me know if it works for you.
Edit
Another way we can make this work is by using a watcher and a computed property.
First add a computed property for the show query param in the route.
computed: {
show() { return this.$router.query.show }
}
Then add a watcher to trigger the focus.
watch: {
show: {
immediate: true,
handler(value) {
document.getElementById(value).scrollIntoView();
}
}
That should work in all cases.

Related

Vue emit data to router view component. Not emitting data and Form submission is cancelled error

I have an array called components at the LiveEdit.vue file data. I want to add an array item which has an object inside to the components array. Everything works fine except the emitting data part. LiveEdit component is on /live url path. The child i'm emitting is NavBarEdit.vue which is on /edit/nav url path. I want to emit data form NavBarEdit to LiveEdit. I also want to change url path to go back to LiveEdit component. I somehow found a way to change routes which is this
this.$emit('addComponent', data)
this.$router.push('/live')
This is my code at LiveEdit vue file
data() {
return {
components: []
}
},
methods: {
addComponent(data) {
this.components = [...this.components, data]
}
},
This is my routes
routes: [
{
path: '/',
component: LandingPage,
},
{
path: '/live',
component: LiveEdit,
},
{
path: '/edit/nav',
component: NavBarEidt,
},
{
path: '/edit/slider',
component: SliderEdit,
}
]
How can I solve this problem? I am really in a trouble with this one. I've been dealing with this like two days. And still no luck. So, please help me out

How to implement the route relative redirects with the query params and the fragment

I have one problem in developing Angular project.
I tried to find the solution on how to implement the route relative redirects with
When the URL redirects, in which origin redirect has its relative the query params and the fragment.
For example, in the guide of Angular.io.
const heroesRoutes: Routes = [
{ path: 'heroes', redirectTo: '/superheroes' },
{ path: 'hero/:id', redirectTo: '/superhero/:id' },
{ path: 'superheroes', component: HeroListComponent },
{ path: 'superhero/:id', component: HeroDetailComponent }
];
in hero-detail, goback() function to navigate back to the HeroListComponent.
I added relativeTo: this.route. But it is not working.
gotoHeroes(hero: Hero) {
let heroId = hero ? hero.id : null;
// Pass along the hero id if available
// so that the HeroList component can select that hero.
// Include a junk 'foo' property for fun.
this.router.navigate(['/heroes', { id: heroId, foo: 'foo' }], {relativeTo: this.route});
}
When configuring to redirect to superheroes, I don't know how to implement this feature.
You need a relative route, so depending on where you are, this should work to go back:
this.router.navigate(['../', { id: heroId, foo: 'foo' }, {relativeTo: this.route}]);
You can use something like -
this.router.navigate(
['hero','12345'],
{
relativeTo: this.route,
queryParams: {
type: 'value',
},
}
);

Get ancestor route params in Angular?

I have the following route hierarchy :
const appRoutes:Routes = [
{
path: 'article',
component: ArticleComponent,
children: [
{
path: '',
component: ArticleListComponent
},
{
path: ':articleId',
component: ArticleDetailComponent,
children: [
{
path: '',
component: PageListComponent
},
{
path: ':pageId',
component: PageComponent
}]
}]
},
{path: '**', component: DefaultComponent},
];
When I click the Article link , the page is navigated to :
"https://run.plnkr.co/article;listData=foo"
And then I see this :
Now , When I click at Article 2 , the page is navigated to
"https://run.plnkr.co/article;listData=foo/2;detailData=bar"
And then I see this :
Now , when I click at the Page 33 link , the page is navigated to :
"https://run.plnkr.co/article;listData=foo/2;detailData=bar/33;detailData=kro"
And then I see this:
OK
As you can see , at the innermost component ( the single page component) , I set some code to see the current params :
Page component! {{params | json}}
Which is populated in :
export class PageComponent {
constructor(private activatedRoute_:ActivatedRoute) {
activatedRoute_.params
.subscribe(params => {
this.params=params;
});
}
Question:
Currently the value of params value - is only { "pageId": "33", "detailData": "kro" } which belongs to the final route.
But how can I get the previous routes values ?
I know I can read the querystring but I find it an unconventional way .
The innermost url is :
"https://run.plnkr.co/article;listData=foo/2;detailData=bar/33;detailData=kro"
So basically I'm asking how can I extract all the parameters from prev routes.
( I mean what are the values for articleId , listData , detailsData (the first one) )?
PLNKR
You can get all parents params using snapshot. In detail component:
let node = activatedRoute_.snapshot;
while(node) {
console.log('component', node.component.name, ', params:', node.params);
node = node.parent;
}
component ArticleDetailComponent ,
params: Object {articleId: "1", detailData: "bar"}
component ArticleComponent , params: Object {listData: "foo"}
component RootComponent , params: Object {}
You should be sending the listData value along with the object.Modify this to your app/article-list.component.ts Component
<a [routerLink]="[articleId, {listData:'foo',detailData: 'bar'}]">
LIVE DEMO
You can manually send params when calling the states inside the links, but to be honest this is not the best solution.
My better suggestion is to use the resolve blocks of the states and implement resolvers in order to achieve that.
Every state will have the corresponding resolver which will resolve the params you need from the previous state.
Here the link to the documentation:
https://angular.io/docs/ts/latest/api/router/index/Resolve-interface.html
The concept is that inside the resolve of the i state, you can still access the state parameters of the i-1 state, so you can pass them to the new state.

router navigation: Outlet is not activated

I'm trying to update my app to use the new v3 router than the angular team just announced http://angularjs.blogspot.com.au/2016/06/improvements-coming-for-routing-in.html and I'm having issues navigating between pages in my app, here are my routes
{ path: '/list', component: UserListComponent, index: true},
{ path: '/payrates', component: AdjustPayrateComponent },
{ path: '/assign', component: AssignUserComponent },
{ path: '/edit/:userId', component: EditUserComponent },
{
path: '/documents',
component: DocumentComponent,
children: [
{ path: '/', component: DocumentComponent, index: true },
{ path: '/:id', component: DocumentComponent },
{ path: '/upload', component: DocumentUploadComponent }
]
},
I want to navigate from the /list page to the /documents/:id page to view documents from a user on the list page.
viewDocuments(user: UserList) {
this.router.navigate(['/documents', { id: user.UserId }], { relativeTo: this.route });
}
However I'm getting the error 'Outlet is not activated' and not sure what this means. I'm basing my app off the example at http://plnkr.co/edit/ER0tf8fpGHZiuVWB7Q07?p=preview
If anyone has any example or advice on how to do navigation with the new router anything would be appreciated, thanks!
figured out the problem, I had a leftover <router-outlet> directive inside my list page, and I guess when trying to navigate from that page the router was trying to load into that bad outlet.

Meteor.js Handlebar Returns different Text depending on current Route in Iron Router

When using Iron Router with Meteor.js 0.8.3, how can I have a text in a view template that changes depending on which route the user is on?
For example, if a user is at /profile, the text would be User Profile and if he is at / the text will be Home.
header.html
<template name="header">
<h1>{{ routeTitle }}</h1>
</template>
profile.html
<template name="profile">
{{> header}}
</template>
router.js
Router.map( function() {
this.route('index', {
path: '/',
template: 'index'
})
this.route('profile', {
path: '/profile/:_id',
template: 'profile',
data: function() { return Users.findOne(this.params._id); }
})
})
I personally store my own properties in the route options like this :
Router.map(function(){
this.route("index", {
// iron-router standard properties
path: "/",
// custom properties
title: "Home"
//
controller: "IndexController"
});
this.route("profile", {
path: "/profile/:_id",
title: "User profile",
controller: "ProfileController"
});
});
Then I extend the Router with a set of utilities functions to access the current route.
_.extend(Router,{
currentRoute:function(){
return this.current()?this.current().route:"";
}
});
UI.registerHelper("currentRoute",Router.currentRoute.bind(Router));
Using these utilities, you can call Router.currentRoute() in JS which happens to be a reactive data source too, as it acts as a wrapper for Router.current().
Use Router.currentRoute() && Router.currentRoute().options.title to check whether there is a current route and fetch the title you declared in the route definition.
In templates you can use {{currentRoute.options.title}} to fetch the current title, this is helpful when working with iron-router layouts.
If you want to get more specific you can even mimic the Router.path and pathFor helper behavior :
_.extend(Router,{
title:function(routeName){
return this.routes[routeName] && this.routes[routeName].options.title;
}
});
UI.registerHelper("titleFor",Router.title.bind(Router));
Now you can call Router.title("index") in JS and {{titleFor "index"}} in templates.
You can even get as far as having a dedicated helper for the current route title, as you suggested in your question :
UI.registerHelper("currentRouteTitle",function(){
return Router.currentRoute() && Router.currentRoute().options.title;
});
You can achieve this very easily with data param of the path:
Router.map(function() {
this.route('...', {
...
data: function() {
return {
importantText: 'User Profile',
};
},
});
});
Now use it as any other data object in your rendered template, layout template, or any of the templates rendered to named area:
{{importantText}}

Categories

Resources