【问题标题】:How to pass props with vue-router and Single File Components如何使用 vue-router 和单文件组件传递道具
【发布时间】:2018-12-21 02:01:18
【问题描述】:

我正在尝试使用视图路由器将道具传递给我的单个文件组件 (.vue),但我仍然在视图扩展名中得到“未定义”。

// Dashboard.vue
<template>
<div class="dashboard" :user="user" :current-team="currentTeam">
    <div class="container">
        <!-- Application Dashboard -->
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card card-default">
                    <div class="card-header">Dashboard</div>

                    <div class="card-body">
                        Your application Dashboard
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</template>


<script>
    export default{
        props: ['user', 'current-team'],

            mounted(){
        //
    }
}
</script>

// app.js
...
import Dashboard from './views/Dashboard.vue';
Vue.component('Dashboard', Dashboard);

const routes = [
  {path: '/dashboard', name: 'dashboard', component: Dashboard, props: true},
];

const router = new VueRouter({
  routes
})
...

未定义

如何正确传递我的道具?非常感谢

【问题讨论】:

    标签: javascript laravel vue.js vuejs2


    【解决方案1】:

    你对 currentTeam 和 user 的价值观从何而来?

    现在看起来您正在尝试将 user 和 current-team 绑定到仪表板组件中的 div 元素,这不会做任何事情。您想以某种方式将您的道具从 app.js 传递给仪表板组件。

    关于你的路线,你已经在你唯一的路线上设置了 props: true 。此设置(称为布尔模式)只是将 route.params 作为您的道具传递给底层组件。但是,您没有在 /dashboard 的路径中指定任何参数(用冒号表示的变量),因此这也不会将任何内容传递给您的组件。

    (例如,路由参数类似于路径:/dashboard/:dashboardId。使用道具:true 这会将参数作为名为dashboardId的道具传递给底层组件。我认为这不是你想要的。)

    一种选择是按照@Squiggs 的建议直接指定路线中的道具。

    您的另一个选择是在 app.js 模板中使用仪表板组件,并以这种方式将道具传递给组件。例如

    //app.js
    <template>
      <div>
        <dashboard :user="userVariable" :currentTeam="currentTeamVariable"></dashboard>
      </div>
    </template>
    

    这也适用于路由器视图,但当您的其他路径不使用这些道具时会变得很尴尬。

    //app.js
    <template>
      <div>
        <router-view :user="userVariable" :currentTeam="currentTeamVariable"></router-view>
      </div>
    </template>
    

    这取决于这些数据的来源以及您希望如何在应用中使用它们。如果需要在整个应用程序中使用应用程序状态数据,那么可能值得研究 Vuex。

    【讨论】:

      【解决方案2】:

      看起来你实际上并没有在路由定义上传递任何东西。

      可能是这样的?您期望什么值?

      {path: '/dashboard', name: 'dashboard', component: Dashboard, props: { currentTeam: currentTeamVariable, user: 'someuser'}
      

      【讨论】:

        猜你喜欢
        • 2020-12-21
        • 2017-03-06
        • 1970-01-01
        • 2018-04-25
        • 2015-09-21
        • 2021-04-03
        • 2021-01-14
        • 2018-12-14
        • 2021-12-02
        相关资源
        最近更新 更多