使用Typescript和类组件装饰器时如何在Vue Router中传递props
Posted
技术标签:
【中文标题】使用Typescript和类组件装饰器时如何在Vue Router中传递props【英文标题】:How to pass props in Vue Router when using Typescript and class component decorator 【发布时间】:2021-03-01 02:56:57 【问题描述】:我试图在使用类组件装饰器时访问我的道具,但我不断返回“未定义”。 Vue Router 上的文档没有记录对使用 TS 的任何支持。下面是我当前的设置和 Codesanbox 的链接。
代码框:
https://codesandbox.io/s/vuetify-ts-router-forked-tsgsu
Router.ts:
import Vue from "vue";
import Router from "vue-router";
import CarsView from "./components/Cars.vue";
import OnboardCarset from "./components/Carsform.vue";
Vue.use(Router);
export default new Router(
mode: "history",
routes: [
path: "/", redirect: "/cars", component: CarsView ,
path: "/cars", component: CarsView ,
path: "/cars/:id",
name: "car-edit",
props: true,
component: OnboardCarset
]
);
Main.js:
import Vue from "vue";
import App from "./App";
import vuetify from "./vuetify";
import router from "./router";
Vue.config.productionTip = false;
/* eslint-disable no-new */
new Vue(
router,
vuetify,
el: "#app",
components: App ,
template: "<App/>"
);
App.vue
<template>
<v-app> <router-view></router-view></v-app>
</template>
<script>
export default
name: "App",
;
</script>
汽车.vue:
<template>
<div>
<router-link :to=" name: 'car-edit', params: id: tab ">
Cars
</router-link>
<router-view name="car-edit" :propsMessage="myArray" />
</div>
</template>
<script lang="ts">
import Component, Vue from "vue-property-decorator";
@Component
export default class Cars extends Vue
public tab: number = 2;
public myArray: Array<string> = [];
constructor()
super();
this.myArray = ["One", "Two", "Three"];
</script>
Carsform.vue
<template>
<div>Cars Form</div>
</template>
<script lang="ts">
import Component, Vue, Prop from "vue-property-decorator";
@Component
export default class Carsform extends Vue
@Prop( type: Array )
propsMessage!: string[];
constructor()
super();
console.log(this.propsMessage);
</script>
【问题讨论】:
【参考方案1】:道具名称应与params
字段相同:
<template>
<div>Cars Form</div>
</template>
<script lang="ts">
import Component, Vue, Prop from "vue-property-decorator";
@Component
export default class Carsform extends Vue
@Prop( type: Number )
id!: number;
constructor()
super();
console.log(this.id);
</script>
【讨论】:
很高兴能帮到你 唯一的事情是在刷新或当我击中路线 "(tsgsu.csb.app/cars/2)" 时,它的重新调整 'undefined'' ,有什么想法吗? 尝试将该日志放入挂载的钩子中 在路由定义中传递该数组,将props:true
替换为props: propsMessage: ["One", "Two", "Three"]
提供该数组作为prop的默认值以上是关于使用Typescript和类组件装饰器时如何在Vue Router中传递props的主要内容,如果未能解决你的问题,请参考以下文章
TypeScript 和 React:如何重载高阶组件/装饰器?
如何使用 TypeScript 在 Vue2.x 类组件中正确注释