什么是vuex-router-sync?

问题描述 投票:21回答:2

据我所知vuex-router-sync只是为了使routevuex store同步,开发人员可以访问route如下:

store.state.route.path
store.state.route.params

但是,我也可以通过更简洁的route来处理this.$route

我什么时候需要在商店中使用路由,以及我需要vuex-router-sync的场景是什么?

vuejs2 vue-router
2个回答
26
投票

这是我的两分钱。如果你不能在你的项目中弄清楚它的用例,你不需要导入vuex-router-sync,但是当你在route的方法中尝试使用vuex对象时你可能需要它(this.$route在vuex的领域不能很好地工作)。

我想在这里举个例子。 假设您要在一个组件中显示消息。除了在用户浏览首页时应显示Have a nice day, Jack的情况,您几乎每个页面都要显示Welcome back, Jack等消息。

您可以在vuex-router-sync的帮助下轻松实现它。

const Top = {
  template: '<div>{{message}}</div>',
  computed: {
    message() {
      return this.$store.getters.getMessage;
    }
  },
};
const Bar = {
  template: '<div>{{message}}</div>',
  computed: {
    message() {
      return this.$store.getters.getMessage;
    }
  }
};

const routes = [{
    path: '/top',
    component: Top,
    name: 'top'
  },
  {
    path: '/bar',
    component: Bar,
    name: 'bar'
  },
];

const router = new VueRouter({
  routes
});

const store = new Vuex.Store({
  state: {
    username: 'Jack',
    phrases: ['Welcome back', 'Have a nice day'],
  },
  getters: {
    getMessage(state) {
      return state.route.name === 'top' ?
        `${state.phrases[0]}, ${state.username}` :
        `${state.phrases[1]}, ${state.username}`;
    },
  },
});

// sync store and router by using `vuex-router-sync`
sync(store, router);

const app = new Vue({
  router,
  store,
}).$mount('#app');












// vuex-router-sync source code pasted here because no proper cdn service found
function sync(store, router, options) {
  var moduleName = (options || {}).moduleName || 'route'

  store.registerModule(moduleName, {
    namespaced: true,
    state: cloneRoute(router.currentRoute),
    mutations: {
      'ROUTE_CHANGED': function(state, transition) {
        store.state[moduleName] = cloneRoute(transition.to, transition.from)
      }
    }
  })

  var isTimeTraveling = false
  var currentPath

  // sync router on store change
  store.watch(
    function(state) {
      return state[moduleName]
    },
    function(route) {
      if (route.fullPath === currentPath) {
        return
      }
      isTimeTraveling = true
      var methodToUse = currentPath == null ?
        'replace' :
        'push'
      currentPath = route.fullPath
      router[methodToUse](route)
    }, {
      sync: true
    }
  )

  // sync store on router navigation
  router.afterEach(function(to, from) {
    if (isTimeTraveling) {
      isTimeTraveling = false
      return
    }
    currentPath = to.fullPath
    store.commit(moduleName + '/ROUTE_CHANGED', {
      to: to,
      from: from
    })
  })
}

function cloneRoute(to, from) {
  var clone = {
    name: to.name,
    path: to.path,
    hash: to.hash,
    query: to.query,
    params: to.params,
    fullPath: to.fullPath,
    meta: to.meta
  }
  if (from) {
    clone.from = cloneRoute(from)
  }
  return Object.freeze(clone)
}
.router-link-active {
  color: red;
}
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script src="https://unpkg.com/vuex/dist/vuex.js"></script>

<div id="app">
  <p>
    <router-link to="/top">Go to Top</router-link>
    <router-link to="/bar">Go to Bar</router-link>
  </p>
  <router-view></router-view>
</div>

fiddle here

正如您所看到的,组件与vuexvue-router的逻辑很好地分离。 对于您不关心当前路由与从vuex的getter返回的值之间的关系的情况,此模式有时可以非常有效。


0
投票

我在学习Vue时看到了这个帖子。增加了我对这个问题的一些理解。

Vuex为Vue应用程序定义了一种状态管理模式。我们使用集中存储来组织由多个组件共享的状态,而不是定义组件道具并通过所有位置的道具传递共享状态。对状态变异的限制使状态转换更清晰,更容易推理。

理想情况下,如果提供的商店状态相同,我们应该获得/构建一致(或相同)视图。但是,由多个组件共享的路由器打破了这一点。如果我们需要推断为什么页面是这样呈现的,我们需要检查存储状态以及路由器状态,如果我们从this.$router属性派生视图。

vuex-router-sync是将路由器状态同步到集中式状态存储的帮助程序。现在可以从州商店构建所有视图,我们不需要检查this.$router

请注意,route状态是不可变的,我们应该通过$router.push$router.go调用“改变”它的状态。在商店中定义一些操作可能会有所帮助:

// import your router definition
import router from './router'

export default new Vuex.Store({
  //...
  actions: {
    //...
    // actions to update route asynchronously
    routerPush (_, arg) {
      router.push(arg)
    },
    routerGo (_, arg) {
      router.go(arg)
    }
  }
})

这包含了商店操作中的route更新,我们可以完全摆脱组件中的this.$router依赖关系。

© www.soinside.com 2019 - 2024. All rights reserved.