javascript - 如何使用 vue-router 和单文件组件传递 props

标签 javascript laravel vue.js vuejs2

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

// 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
})
...

未定义 enter image description here

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

最佳答案

您对当前团队和用户的值(value)观从何而来?

现在看起来您正在尝试将用户和当前团队绑定(bind)到仪表板组件中的 div 元素,这不会执行任何操作。您希望以某种方式将 props 从 app.js 传递到仪表板组件。

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

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

一种选择是按照 @Squiggs 的建议直接指定路由中的 props。

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

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

这也适用于 router-view,但是当您的其他路径不使用这些属性时会变得很尴尬。

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

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

关于javascript - 如何使用 vue-router 和单文件组件传递 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51312406/

相关文章:

vue.js - 使用 Jasmine 在 Vue 组件中测试方法

javascript - Angular 8 使用 ngIf 和异步管道来显示和隐藏 HTML 元素

php - Laravel API 对后续请求的验证/保护 : no login/logout and no "users" table

python - 为什么 Laravel Redis::scan ('*' ) 返回预期的 key ,但 Redis::keys ('*' ) 没有返回?

vue.js - sass-loader additionalData/prependData/data bloats 包大小

javascript - 数据变量未从 VueJS 中的方法更新

javascript - 将状态传递给 react-router 1.x

javascript - Google 未将 _escaped_fragment_ 用于主页

javascript - 允许使用 JavaScript 正则表达式将金额输入到输入中

php - Laravel 集合分组依据