【问题标题】:How to get a key from route module using vuex-router-sync如何使用 vuex-router-sync 从路由模块获取密钥
【发布时间】:2017-10-25 01:54:18
【问题描述】:

我有一个小的 Vuex 商店(如下所示),我使用 vuex-router-sync 来保持同步。这会在我的商店中添加一个 router 模块,但是我如何将这个对象从商店中取出,因为该模块似乎没有任何关联的 getter?

存储/index.js

import Vue from 'vue'
import Vuex from 'vuex'

import module1 from './modules/module1'
import module2 from './modules/module2'
import module3 from './modules/module3'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    module1,
    module2,
    module3
  }
})

main.js

import App from './views/App/App'
import store from './store'
import router from './router'
import { sync } from 'vuex-router-sync'

// sync router with store
sync(store, router)

new Vue({
  el: '#app',
  store,
  router,
  render: h => h(App)
})

我的状态应该是这样的:

{
  module1: {
    cheese: true
  },
  module2: {
    crackers: true
  },
  module3: {
    wine: true
  },
  route: {
    from: {}
    fullPath:"/path/to/cheese"
    hash:""
    meta: {}
    name:"cheese"
    params: {}
    path:"/path/to/cheese"
    query: {}
  }
}

基本上我要做的是在我的应用标题中添加一个标题,该标题会根据您所在的页面/视图进行更新。

Header.vue

export default {
  name: 'header',
  computed: {
    getRouteTitle () => {
      return this.$store.getters.getRouteTitle
    }
  }
}

Header.html

<header>
 <h1>{{ getRouteTitle }}</h1>
</header>

【问题讨论】:

    标签: javascript vue.js vuejs2 vuex


    【解决方案1】:

    找到了一个效果很好的解决方案。 vuex-router-sync 触发一个动作来告诉我们路由已经改变。在我们现有的模块之一中,您可以从中听出并进行后续突变。对我来说,这将是从 router/ROUTE_CHANGED 操作负载中设置 title

    路由器.js

    const router = [
      {
        name: 'Cheese',
        path: 'cheese',
        component: Cheese,
        meta: { title: 'Calendar', requiresAuth: true }
      },
    ]
    

    module1.js

    import * as types from '../mutation-types'
    
    // Initial State
    const state = {
     cheese: true,
     title: 'App'
    }
    
    // Getters
    export const getters = {
      getRouteTitle: state => state.title
    }
    
    // Mutations
    export const mutations = {
      'router/ROUTE_CHANGED' (state, payload) {
        state.title = payload.to.meta.title
      }
    }
    
    export default {
      getters,
      mutations,
      state
    }
    

    希望这是有道理的,如果有更好的解决方案,请告诉我:)

    *********更新*********

    一个超级简单的方法就是像这样在你的组件中获取$router 实例:

    <h1>{{$route.name}}</h1>
    

    这将呈现到:

    <h1>Cheese</h1>
    

    【讨论】:

      猜你喜欢
      • 2021-05-05
      • 2017-10-25
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      • 2011-09-28
      • 2013-03-17
      相关资源
      最近更新 更多