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

时间:2017-03-26 13:00:00

标签: javascript vuejs2 vue-router

我在处理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个城市......我怎么能解决这个问题?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

如果某人需要根据路线实施数据传输,并且真的想将其硬编码为路由文件,则可以使用: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从后端获取数据是最好的。

相关问题