如何根据路由和使用 vue-route 更改 Vue 组件中的数据 object?

How can I change data object in Vue component depending on route and using vue-route?

我在处理 vuejs 应用程序时遇到问题:

我必须根据路由更改几个 vuejs 组件中的标题

routes: [ { path: '/', components: { //with default data FirstScreen, Advantages, Slider, }, }, { path: '/moscow', components: { //with special data for Moscow FirstScreen, Advantages, Slider, }, }, { path: '/berlin', components: { //with special data for Berlin FirstScreen, Advantages, Slider, }, }, ],

所有 .vue 文件中的数据如下所示

data() {
  return {
    defaultTitle: 'some string',
    defaultArray: ['defaultFirst', 'defaultSec'],
  };
},

我有大约 100 个城市...我该如何解决这个问题?

假设您使用 vue-router,您可以 'hook into' 其中一个非常有用的方法叫做 beforeEach。此方法充当一种中间件,并在执行任何给定路由之前运行。

router.beforeEach((to, from, next) => {
    document.title = to.meta.title
    next();
});

如果有人需要根据路由实现数据传输并且真的想将其硬编码为路由文件,则可以这样做:https://github.com/vuejs/vue-router/blob/dev/docs/en/essentials/passing-props.md

在我的例子中,它看起来像:

routes: [
{
  path: '/',
  components: {
    FirstScreen,
    Advantages,
    BigSlider,
  },
  props: {
    FirstScreen: {
      title: 'title',
      subtitle: ['arr1', 'arr2'],
    },
    Advantages: {
      title: 'title',
      advantages: 'advantages',
    },
    BigSlider: {
      title: 'title',
      slideText: 'slideText',
    },
  },
},

并且在组件中你必须做这样的事情

export default {
props: {
  title: {
    type: String,
  },
  subtitle: {
    type: Array,
  },
},

它会工作得很好,但我部分同意 Kevin Karsopawiro 的观点,即这种方法无法维护。因此,在我的情况下,最好使用 city-component 从后端获取数据。