2017-06-16 104 views
2

我正在嘗試創建一個模式路由,並且當您使用路由器鏈接訪問此路由器路徑時,會在當前頁面上方顯示一個模式,或者如果我直接從URL訪問上面的模態指數。Vuejs2 Modal with vue-router

例如:我在http://localhost/profile/1並點擊側邊欄創建團隊URL更改爲http://localhost/team/creat,但模態後面的頁仍爲http://localhost/profile/1

這是我想要的代碼:

路由器:

Vue.component('modal', Modal);  
export default new Router({ 
     mode: 'history', 
     routes: [ 
     { 
     path: '/', 
     name: 'Hello', 
     component: require('@/components/Hello'), 
     meta: { auth: false } 
     }, 

     { 
     path: '/team', 
     name: 'team', 
     component: require('@/components/team/Index'), 
     meta: { auth: true }, 
     }, 
     { 
     path: '/team/create', 
     name: 'CreateTeam', 
     components: { 
      b: CreateTeam 
     }, 
     meta: { auth: true } 
     }, 
     ] 
    }) 

App.vue

<template> 

    <router-view></router-view> 
<!--This is the "MODAL" router-view --> 
    <router-view name="b"></router-view>    

</template> 

Modal.vue

<template> 
    <div class="modal"> 

     <slot name="body"></slot> 
     <button type="button" @click="$emit('close')">×</button> 
    </div> 
</template> 

CreateTeam.vue

<template> 
    <modal @close="vm.$router.go(-1)"> 

     <div slot="body" class="col-md-12"> 
     Form here 
     </div> 

    </modal> 
</template> 

一切工作,而不是當我去/製作/團隊背後的模式是空的

+0

你的模式不應該在這種情況下,路由,它應該是相同的部件的要素是放置你的'路由器視圖'。當需要顯示它時,使用事件或狀態管理從該組件中觸發它,甚至通過'router-view'將一個函數傳遞給需要觸發它的組件。 – Bert

+0

我明白,但在這種情況下,我想打開任何組件像「全球模式」。如果我喜歡你說所有的組件都必須有模態組件和diferents路徑的代碼ex:profile/modal,team/modal「我想在任何地方打開團隊/創建 – Snickfire

+0

不,這不是我它應該生活在App.vue中,它不應該是一個路線,你的組件*是路線應該觸發它。 – Bert

回答

2

如果有人需要這樣的解決方案,我解決了這個辦法:

我創建了一個組件創建團隊Vue.component(「創建團隊」,CreateTeam),我把它放在App.vue這樣的:

<create-team v-if="CreateTeam"></create-team> 

同樣App.vue我創建了一個計算與vuex消氣:

computed: { 

    CreateTeam() { 
     return store.getters.createTeam 
    } 
    }, 

在邊欄我創建這樣的鏈接:

<a @click="CreateTeam" class="user-panel-action-link" href="/create/team"> 
    <i class="fa fa-users" aria-hidden="true"></i> Crear Equipo 
</a> 

和一種方法CreateTeam

CreateTeam(e) { 
     e.preventDefault() 
     store.commit('setTeamModal') 
     history.pushState('', 'Title of page', '/create/team'); 

    } 

的store.js vuex很簡單:

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 
}) 

而最後一件事是在CreateTeam.vue組件中,我使用如下的Close方法:

Close() { 
     this.$store.commit('deleteTeamModal') 
     this.$router.go(-1) 
    } 

    } 

也許有人可以做的更好,這是我的小片的幫助

問候

+0

不錯的一個!也會給你一個嘗試 - 很好的瞭解'history.pushState(..)'只適用於vue-router。 – Hartmut