SpineJS stack doesn't add active class to controllers - spine.js

Spine = require('spine')
Welcome = require('controllers/welcome')
Signup = require('controllers/signup')
class Main extends Spine.Stack
controllers:
welcome: Welcome
signup: Signup
default: 'signup'
routes:
'/welcome': 'welcome'
'/signup': 'signup'
module.exports = Main
The welcome and signup controllers just render a view so I can understand how the stack works:
Spine = require('spine')
class Welcome extends Spine.Controller
className: 'welcome'
constructor: ->
super
#active #render
render: ->
console.log 'welcome render function'
#html require('views/welcome')()
module.exports = Welcome
and then per stack docs, I added this to my css:
.stack > *:not(.active) {
display: none
}
I purposefully have the signup controller do #navigate('/welcome') instead of rendering its view to see how I would control the stack. The console.log statement in welcome's render function does get called, however welcome's <div> doesn't have the active class added to it, and because of the above CSS, isn't shown.
I've re-read the docs a few times, googled around, and am not sure what I'm missing. Why isn't the active class being added to the welcome el?

I suspect that the problem is that you're calling render as part of the active event, which is happening after the class is added. Since render calls #html, it would replace the HTML that had the class added.
As an aside, with spine I've found that reading the source code can help immensely. It's a tiny framework. See https://github.com/spine/spine/blob/dev/src/manager.coffee for the relevant code for stacks.

Related

Why does the browser display cached Vue.js view on route/url change?

I have a homepage with <router-link> tags to views. It is a simple master/detail relationship where the Homepage is a catalogue of products and the Product detail page/view shows information on each item.
When I first launch the website and click on an item on the Homepage view (e.g. URL: http://localhost:8080/100-sql-server-2019-licence), the Product view gets loaded and the product detail loads fine.
If I then press the back button in the browser to return to the Homepage and then click on a different Product (e.g. URL: http://localhost:8080/101-oracle-12c-licence), the URL in the browser address bar changes but I get the previous product's information. Its lightning quick and no new network calls are done which means its just showing a cached page of the previous product. If I then hit the refresh button while on that page, the network call is made and the correct product information is displayed.
I did a search online but couldn't find this problem described on the search results. Could anyone point me in the right direction of how to cause a refresh/re-render of a route when the route changes?
What is happening
vue-router will cache your components by default.
So when you navigate to the second product (that probably renders the same component as the first product), the component will not be instantiated again for performance reasons.
From the vue-router documentation:
For example, for a route with dynamic params /foo/:id, when we
navigate between /foo/1 and /foo/2, the same Foo component instance
will be reused.
The easy (but dirty) fix
The easy -but hacky and not recommended - way to solve this is to give your <router-view /> a key property, e.g.:
<router-view :key="$route.fullPath" />
This will force vue-router to re-instantiate the view component every time the url changes.
However you will loose all performance benefits you would normally get from the caching.
Clean fix: properly handling route changes
The clean way to solve this problem is to react to the route-change in your component (mostly this boils down to moving ajax calls from mounted into a $route watcher), e.g.:
<script>
export default {
data() {
return {
productDetails: null,
loading: false
};
},
watch: {
'$route': {
// with immediate handler gets called on first mount aswell
immediate: true,
// handler will be called every time the route changes.
// reset your local component state and fetch the new data you need here.
async handler(route) {
this.loading = true;
this.productDetails = null;
try {
// example for fetching your product data
const res = await fetch("http://give.me.product.data/" + encodeURIComponent(route.params.id));
this.productDetails = await res.json();
} finally {
this.loading = false;
}
}
}
}
};
</script>
Alternative: Navigation Guards
Alternatively you could also use vue-routers In-Component Navigation Guards to react to route changes:
<script>
export default {
async beforeRouteUpdate (to, from, next) {
// TODO: The route has changed.
// The old route is in `from`, the new route in `to`.
this.productData = await getProductDataFromSomewhere();
// route will not change before you haven't called `next()`
next();
}
};
</script>
The downside of the navigation guards is that you can only use them directly in the component that the route renders.
So you can't use navigation guards in components deeper within the hierarchy.
The upside is that the browser will not view your site before you call next(), which gives you time to load the data necessary before your route is displayed.
Some helpful ressources
Vue Router Navigation Guards Documentation
vue-router github issue
Similar Question about vue-router component reuse on stackoverflow

Vuejs component reuse on navigation change - clarification sought

In the following example, if the user navigates from /user/foo to /another_page and then to /user/bar, will the User component be reused?
const User = {
template: '<div>User</div>'
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User }
]
})
The Vue Router manuals says ...
One thing to note when using routes with params is that when the user navigates from /user/foo to /user/bar, the same component instance will be reused. Since both routes render the same component, this is more efficient than destroying the old instance and then creating a new one. However, this also means that the lifecycle hooks of the component will not be called.
Dynamic Route Matching
... but it's not clear whether the component is only reused when there are no intermediary navigation steps. Is there any documentation that discusses component reuse in this kind of detail?
Thanks!
If you navigate from /user/foo to /user/bar then the component will be reused.
This is often used when displaying product page for example. Note that there are ways to rebuild component if it is needed.
If you will navigate from /user/foo to /another_page and then navigate to /user/bar then your component will be destroyed when leaving to /another_page and created when navigating to /user/bar.
To sum up:
/user/foo -> /another_page - component gets destroyed
/user/foo -> /user/bar - component will be reused

Vue router reloading the current route

Without reloading the whole page I need to reload the current route again (Only a component reload) in a vue app.
I am having a path in vue router like below,
{
path: "/dashboard",
name: "dashboard",
component: loadView("Dashboard"),
},
When user clicks on the Dashboard navigation item user will be redirected to the Dashboard page with vue router programmatic navigation
this.$router.push({ name: "dashboard" });
But when user already in the dashboard route and user clicks the Dashboard nav item again nothing happens. I think this is vue router's default behaviour. But I need to force reload the Dashboard component (Not to refresh the whole page).
I can't use beforeRouteUpdate since the router is not updated. Also I have tried the global before guards like beforeEach. But it is also not working.
How can I force reload the dashboard component without reloading the whole page?
It can be done in two ways.
1) Try doing vm.$forceUpdate(); as suggested here.
2) You can take the strategy of assigning keys to children, but whenever you want to re-render a component, you just update the key.
<template>
<component-to-re-render :key="componentKey" />
</template>
<script>
export default {
data() {
return {
componentKey: 0,
};
},
methods: {
forceRerender() {
this.componentKey += 1;
}
}
}
</script>
Every time that forceRerender is called, the prop componentKey will change. When this happens, Vue will know that it has to destroy the component and create a new one.
What you get is a child component that will re-initialize itself and “reset” its state.
Not mentioned here, but as the offered solutions require a lot of additional work just to get the app to render correctly, which imo is a brittle solution.. we have just implemented another solution which works quite well..
Although it is a total hack.
if (this.$route.name === redirect.name) {
// this is a filthy hack - the vue router will not reload the current page and then have vue update the view.
// This hack routes to a generic page, then after this has happened the real redirect can happen
// It happens on most devices too fast to be noticed by the human eye, and in addition does not do a window
// redirect which breaks the mobile apps.
await this.$router.push({
name: RouteNames.ROUTE_REDIRECT_PLACEHOLDER
});
}
... now continue to do your normal redirect.
Essentially, redirect to a placeholder, await the response but then immediately continue to another page you actually wanted to move toward

Element UI NavMenu gets out of sync with current route

I'm using the Element UI NavMenu with :router="true". It is working fine when I click on menu links (route changes and active menu item changes). The issue I'm having is that when I click on the browser navigation buttons (back and forward), the route and component change, but the NavMenu active tab does not change.
Is there an easy way to make sure the NavMenu and current route stay in sync with each other when using the browser navigation buttons? I'm using vue-router with mode: 'history'. I would have thought that this would be handled automatically.
I originally tried to implement this answer with no luck. I now have a working solution for this issue. In my navigation component, I have an el-menu with :router="true" and:default-active="activeLink"`.
Since I have a fairly simple Vue application, I did not want to loop over my router paths and build the NavMenu dynamically. This is a good practice, but I wanted to understand how it works at a basic level first.
From the element-ui docs, default-active controls the index of currently active menu. I added activeLink as a data property:
data() {
return {
logo: logo,
activeLink: null,
}
},
and then added a watch property as described in the gist linked above:
watch: {
$route (to, from) {
this.activeLink = to.path;
}
},
The part I was missing was that the index and the route properties of the el-menu-item need to be the same. Also, we can add a mounted method to make sure that the correct nav link is made active no matter what path we load the app from:
mounted: function(){
this.activeLink = this.$route.path;
},
That fixed the issue of the NavMenu getting out of sync when I use browser navigation buttons.
This was a pain to get to work. I couldn't get beforeRouteUpdate() to work at all, and :default-active="$route.path" almost works, but not if you have parameters for your routes. My current solution is to name all of my routes, and add menu items where the index is the name. Then the default-active value can just be taken from $route.name.
<el-menu :default-active="$route.name" #select="menuSelect">
<el-menu-item index="summary">
<span slot="title">Summary</span>
</el-menu-item>
<el-menu-item index="memory">
<span slot="title">Memory Overview</span>
</el-menu-item>
...
</el-menu>
And in your component:
public menuSelect(index: string) {
this.$router.push({
name: index,
});
}
You can also avoid the annoying error Navigating to current location ("summary") is not allowed like this:
public menuSelect(index: string) {
if (this.$route.name !== index) {
this.$router.push({
name: index,
});
}
}

how to get a splash screen first and then go the main home screen when using react-native-navigation?

I am using react-native 0.32.0 and "react-native-navigation": "^1.0.30", And I want to get a splash screen first and then go to the main home screen, where I begin to use react-native-navigation. I googled a lot and did a lot re research but still do not know how to make this. I try to get the simplest config passed to Navigation.startSingleScreenApp, but I still get the navbar in iOS. is it possible to get a raw splash screen first and then use react-native-navigation for navigation?
I implemented this through navigation experimental itself. you can refer this repository on github for navigation experimental https://github.com/jlyman/RN-NavigationExperimental-Redux-Example
I used setTimeout() function in the constructor of the page which I am loading first through my navigation experimental. The page in which I used this function became the splash screen of my app. Here is the code.
class FirstScreen extends Component{
constructor(props) {
super(props);
setTimeout(this.props.OnChange, 3000); //Constructor of Splash Screen page
}
//render() code
}
and here is my onChange() function inside mapDispatchToProps() which is calling navigatePush() action creater of my navigation experimental
OnChange: () => {
dispatch(navigatePush('Login'))
}