javascript - 如何使用 vuex-router-sync 从路由模块获取 key

标签 javascript vue.js vuejs2 vuex

我有一个小 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: {}
  }
}

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

标题.vue

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

标题.html

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

最佳答案

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

路由器.js

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

模块1.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
}

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

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

一个 super 简单的方法就是在组件中获取 $router 实例,如下所示:

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

这将呈现为:

<h1>Cheese</h1>

关于javascript - 如何使用 vuex-router-sync 从路由模块获取 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44163147/

相关文章:

javascript - Vuejs :ajax validation error messages not displaying

javascript - 如何使用 Vue 构建 UI 框架

javascript - VueJS 点击事件不起作用

javascript - 如何获取ios中UIWebview中的内容

javascript - 使用 Jquery 自动向下滚动?

javascript - 用javascript出现onclick效果?

javascript - 找不到 Vue.js $ref

jquery - 使用 Vuejs 的日期选择器

javascript - 如何从散点图中选择一个点并显示有关它的数据?

javascript - 如何排除 v-for 中的最后一项?