首页 文章

Vue Router将道具传递给动态加载的子项

提问于
浏览
1

我正在学习Vue atm,而且我很难通过Vue Routes在子组件和父组件之间传递道具 . 我有一个Layout组件,它有一个包装器DIV,看起来像这样:

<template>
    <div class="container" v-bind:class="cssClass">
      <router-view></router-view>
    </div>
</template>

<script>
export default {
  name: 'Layout',
  props: ['cssClass']
}
</script>

我已经在我的基础App JS中定义了我的路线,如下所示 . 所以我对第一次加载的看法有“容器动画”这个类,所有对世界都很好 .

const router = new VueRouter({
    routes: [
      { path: '/', component: Layout, props: { cssClass: 'container-animated' },
        children: [
          { path: '', component: Homepage },
          { path: '/hello-world', component: HelloWorldPage, props: { cssClass: '' } }
        ]
     },
    ]
});

但是,一旦我点击/ hello-world路径,我想将一个空的cssClass道具传递给布局,(HelloWorldPage当前嵌套在里面) - 我该怎么做?道具甚至是实现这一目标的机制吗?

2 回答

  • 0

    让我解释一下vue是如何工作的:

    你得到了你的父组件 . Layout.vue

    <template>
      <div id="app" class="container-fluid">
        <router-view/>
      </div>
    </template>
    <style>
     .container-fluid {
    background-color:blue; //as defined in the parent, everything inside #app will inherit this class
    }
    </style>
    

    现在,您的vue路由器必须如下所示:

    {
        path: '/',
        name: 'Layout',
        component: Layout,
        children: [
            { path: '', component: Create, name: 'Create' },
        ]
    }
    

    由于您已经定义了Layout.vue内部将继承.container-fluid内的所有内容,因此组件Create将继承其父级(Layout)中定义的类 .

    希望这有效 .

    问候,

  • 0

    我想通了,这是否是我的问题的最佳解决方案是任何人的猜测 .

    在Vue路由器上传递时,父母不会自动拾取子道具 . 因此,一旦动态构建/注入组件,它们每个都调用我的自定义childinit事件,该事件将发回到父(布局)中定义的路由器视图 . 我在父项中将局部变量设置为发出的子项的值,然后将该类绑定到它 .

    const router = new VueRouter({
        routes: [
          {
            path: '/',
            component: Layout,
            children: [
              {
                path: '',
                component: Homepage,
                props: { cssClass: 'home' },
              },
              {
                  path: '/helloworld',
                  component: HelloWorldPage,
                  props: { cssClass: 'helloworld' }
              }
            ]
          }
        ]
    });
    

    我的布局组件:

    <template>
        <div class="container" v-bind:class="className">
          <router-view v-on:childinit="onChildInit"></router-view>
        </div>
    </template>
    
    <script>
    export default {
      name: 'Layout',
      props: ['cssClass'],
      data() {
        return {
          className : ''
        }
      },
      methods: {
        onChildInit( value ){
          this.className = value;
        }
      }
    }
    </script>
    

    我的主页组件:

    export default {
      name: 'Homepage',
      props: ['cssClass'],
      created() {
        this.$emit('childinit', this.cssClass);
      }
    }
    

    HelloWorld组件也会发出,创建的方法可能不需要复制;可能会看看你是否可以扩展一个总是在init上为两个组件发出的基本组件 .

相关问题