Vue.js Routing with back button - javascript

I already use this Vue.js Routing example application.
https://github.com/chrisvfritz/vue-2.0-simple-routing-example
In the src/main.js
I have so much data value .
const app = new Vue({
el: '#app',
data: {
currentRoute: window.location.pathname,
token : "",
errorMessage : '', etc...etc..
},
Now with socket.io i set the token to "sdawdda2d2ada2ad22ad"
When application start than the currentRoute is equal with "/"
Its okey, the first page loaded. src/routes.js
'/': 'Home',
'/about': 'About'
When i want to check the /about (url: localhost:8080/about), than its works good , but the token and errorMessage is empty again, because the app created again.
If i want to change page without lose the token value i can use:
this.currentRoute = "/about" (url: localhost:8080)
Its works good , but the url not change, so i cant use back button in browser.
How can i separate my Vue app, if i dont want to lose token value when the browser go to /about?
Thanks so much!

you can do something like this.$router.go(-1) or vm.$router.go(-1) to go forward this.$router.go(1) for more click here

simple way
<template lang="html">
<div>
<button #click="goBack">
Back
</button>
</div>
</template>
<script>
export default {
methods: {
goBack() {
this.$router.go(-1)
}
}
}
</script>

When you are moving from your Home route to About route, you need to use <router-link> to navigate.
From your home page, you can navigate to about page as follows:
<router-link to="/about">Go to my About Page</router-link>
That generates a regular html anchor tag <a> with the path set correctly. When you click on that, it will take you to the about component, and not refresh the entire html webpage (with app scripts) from server.
When only the route component gets changed, all your other Vue params like token on the Vue instance will remain.
Please take a look at the vue-router here: http://router.vuejs.org/en/essentials/getting-started.html
Remember to have a placeholder for routes in your main app as follows: <router-view></router-view>. Your Home and About component will get rendered into this router-view as you change routes.

Related

Keep param consistent on location change ReactJs

I am using react router v4 to change location in ReactJs.
this.props.history.push("/profile");
<Link to="/profile" />
The above code works fine.
Now I want to keep a param consistent in URL http://localhost:3000?source=test by using the same code as above.
One approach is that I find all the occurrences in the code and add condition that if params source=test exist then append it to the the URL as well but this approach doesn't look fine to me as I have add condition on every redirect, Link and history.push
Second approach that I find is that use of listener on location update given by react router
In my Main Route file
class App extends Component {
componentDidMount() {
this.unlisten = this.props.history.listen((location, action) => {
if (/source=ep/.test(this.props.location.search)) {
location.search = _startsWith(location.search, "?") ? location.search + "&source=test" : "?source=test"
}
});
}
}
With this approach I can easily append the params in search query of react router but the param doesn't show up in URL.
the URL looks like this http://localhost:3000/profile and When I get search params from react-router console.log(this.props.location.search) it shows the param source=test and it's exactly what I want but In this case if user refreshes on this page the search params lost from react-router as well because it's not in the URL.
Can you guys help me to keep source=test consistent even in URL.

React Router Redirect component not giving the desired result

I am trying to redirect in react. But is not getting redirected to the desired place.
Here is the code:
<Redirect to={"https://www.google.com"} />
Now it is getting redirected to http://localhost:3000/https://www.google.com.
Could someone help me in this?
I would suggest to use instead <Link> component. That will generate for you an <a> tag with the required URL. <Redirect> component is for changing the route in application level.
<Link>: Provides declarative, accessible navigation around your application.
<Redirect>: Rendering a <Redirect> will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.
Try as the following:
<Link to={'https://www.google.com'}>Go to Google</Link>
I hope this explains!
Seems like you are navigating away from your current website. In that case, you shouldn't be using <Redirect>. The <Redirect> component is meant to be used to redirect to another route within your app, not to an external website. The reason you get redirected to http://localhost:3000/https://www.google.com is because React Router treats the passed in to prop as a relative path, and appends it to the current host, which is http://localhost:3000.
If you want to do an external redirect, you don't need to use a <Redirect> component in this case, just use JavaScript:
window.location = 'https://www.google.com';
If you want to have a component that redirects when it mounts, you can use this component which contains a useEffect hook:
function ExternalRedirect({href}) {
React.useEffect(() => {
window.location = href;
});
return null;
}
// In your code:
<ExternalRedirect href="https://www.google.com" />

Vue.js - Loading alternative component when dynamic variable does not exist

I've been struggling with this for a few days and was hoping for a graceful way of handling dynamic URLs with no data.
I have the following routes:
const router = new VueRouter({
routes: [
{path: '/product/:slug', component: Product},
{path: '/404', component: PageNotFound, alias: '*'}
]
});
In the Product component, I have an object of products and, depending on the slug variable, load the product to show.
The issue i'm having is when the URL is a slug that does not exist in the products dataset. I would like to load the PageNotFound component, without updating the URL.
Is this possible? It would be nice to have a consistent 404 page throughout the app and would also be good for me not to have to repeat myself with a v-if in the product table.
The closest I've got to it is this:
if(!product) {
this.$router.replace({path: '/404', query: {product: this.$route.params.slug}});
}
However, this updates the actual URL which is not very good UX.
Any clues?
You could conditionally render your PageNotFound component in Product.vue if the query returns no results, and then not have to fiddle with your router at all.
Thanks to Kyle pointing me in the right direction, this is what I came up with.
Becuase I am being slightly unorthodox and using server-side components and JavaScript, I already had my page not found component loaded - which looks like this:
const PageNotFound = {
name: 'PageNotFound',
template: `<div>
<h1>404 Page Not Found</h1>
<p>Head back to the <router-link to="/">home page</router-link> and start again.</p>
</div>`
};
I made sure the PageNotFound.js file was loaded in the HTML before my product component, so I was able to do the following:
const ProductPage = {
name: 'ProductPage',
template: `<div>
<div v-if="product"><h1>{{ product.title }}</h1></div>
<page-not-found v-if="notFound"></page-not-found>
</div>`,
components: {
PageNotFound
},
data() {
return {
notFound: false
}
},
computed: {
product() {
let product;
if(Object.keys(this.$store.state.products).length) {
product = this.$store.state.products[this.$route.params.slug];
if(!product) {
this.notFound = true;
}
}
return product;
}
}
};
Things to note in the above:
Data is being loaded asynchronously, hence the check to see if products exist
The PageNotFound component is loaded in - this is ES6 for PageNotFound: PageNotFound - Vue then automatically makes a <page-not-found></page-not-found> element
That element then has a v-if which gets triggered. As the first container would not be in existence if there is no product, only the 404 component is displayed
I don't do it based on product, as you would get a flash of the 404 if the product data was still loading via an API.
It's better practice to have the URL params as props (see docs), which I will be doing at some point!
To conclude, this allows you to show a consistent 404 page throughout your SPA (single page application) while maintaining URLs with dynamic routes. It allows you to load another component or show another component without updating the URL and also lets you have a wildcard 404 for dynamic routes.
Hope that all makes sense and helps someone in the future and saves them from wasting ~4 hours of trial, error and googling. (and yes I have "keyword" and phrase stuffed this answer to help someone find it...)

Refresh / Reload ember route from a component

I have a component, that's actually a modal dialog.
When I am done with that dialog and press the "Ok" button, I want to stay on the stay page from where I opened that dialog.
Which isn't difficult.
But the problem is that the dialog changes the data (I am getting data through a REST call) so I need to refresh the route that I already am on to reflect the data changes.
Since, I am calling it from a component, I don't have Route so can't call route.refresh().
I tried to get the router:
this.set('router', Ember.getOwner(this).lookup('router:main'));
and did transition to the same page:
_this.get('router').transitionTo('my-route')
But since the route hasn't changed (I only opened a dialog), transitionTo doesn't get triggered!
Is there a way I can force trigger transitionTo or refresh the page that I am on?
Thank you!
First, you can easily get the current route name by injecting the routing service to the component.
Then, you can get the current route instance and apply its refresh method:
// app/components/a-component.js
import Component from "ember-component";
import service from "ember-service/inject";
import getOwner from "ember-owner/get";
export default Component.extend({
routing: service("-routing"),
actions: {
refresh() {
const currentRouteName = this.get("routing.currentRouteName");
const currentRouteInstance = getOwner(this).lookup(`route:${currentRouteName}`);
currentRouteInstance.refresh();
}
}
});
For this, define refreshCurrentRoute method in nearest route or in application route file.
actions:{
refreshCurrentRoute(){
this.refresh();
}
}
From your component, you need to call refreshCurrentRoute action. either you can use ember-route-action-helper or by passing the closure action.

Why the router.go() does not work in Vue Router?

Using vue-router, I have a component check user login status, how can I redirect to the login page URL using the router?
In component, my code:
<script>
export default {
components: {
},
name: 'landing-page',
created: function () {
const router = this.$router
router.go({path: '/login'})
}
}
</script>
But router.go does not work.
Oh, use router.push('/login') can working fine.
Remember that router.go takes a single integer parameter that indicates by how many steps to go forwards or go backwards in the history stack. So to give a path you should use router.push('your_url').
For more information I suggest you read this:
Vuerouter

Categories

Resources