Vuejs2 Modal with route in vue-router
If somebody else search for solution for similar problem nice one is presented here.
Before redirect to modal route programmatically change components of named routes. Worked for me like a charm with Login/Signup modals.
My notes:
1. Make sure modal routes are not child of any route (I had some problems with default route component).
2. Consider to add router.back()
on modal close button.
router.js
...
{
path: '/',
name: 'home',
component: Home,
meta: {
twModalView: true
}
},
{
path: '/directAccess',
name: 'directAccess',
component: DirectAccess
},
...
{
path: '/:userId/tweet/:id',
name: 'userTweet',
beforeEnter: (to, from, next) => {
const twModalView = from.matched.some(view => view.meta && view.meta.twModalView)
if (!twModalView) {
//
// For direct access
//
to.matched[0].components = {
default: TweetSingle,
modal: false
}
}
if (twModalView) {
//
// For twModalView access
//
if (from.matched.length > 1) {
const childrenView = from.matched.slice(1, from.matched.length)
for (let view of childrenView) {
to.matched.push(view)
}
}
if (to.matched[0].components) {
to.matched[0].components.default = from.matched[0].components.default
to.matched[0].components.modal = TweetModal
}
}
next()
}
},
...
If anyone needs this solution, i solved this way:
I created a component create-team Vue.component('create-team',CreateTeam) and i put it in the App.vue like this:
<create-team v-if="CreateTeam"></create-team>
In the same App.vue i created a computed with a vuex getter:
computed: {
CreateTeam() {
return store.getters.createTeam
}
},
In Sidebar i created a link like this:
<a @click="CreateTeam" class="user-panel-action-link" href="/create/team">
<i class="fa fa-users" aria-hidden="true"></i> Crear Equipo
</a>
And a method CreateTeam
CreateTeam(e) {
e.preventDefault()
store.commit('setTeamModal')
history.pushState('', 'Title of page', '/create/team');
}
The store.js vuex is simple:
const state = {
createTeam: false,
}
const mutations = {
setTeamModal (state) {
state.createTeam= true
},
deleteTeamModal (state) {
state.createTeam= false
}
}
const actions = {
setTeamModal: ({ commit }) => commit('setTeamModal')
deleteTeamModal: ({ commit }) => commit('setTeamModal')
}
const getters = {
createTeam: state => state.createTeam
}
export default new Vuex.Store({
state,
getters,
actions,
mutations
})
And the last thing is in the CreateTeam.vue component the Close method i made somthing like this:
Close() {
this.$store.commit('deleteTeamModal')
this.$router.go(-1)
}
}
Maybe someone can make it better, that's my little piece of help
Greetings