【问题标题】:How to pass props in Vue Router when using Typescript and class component decorator使用Typescript和类组件装饰器时如何在Vue Router中传递props
【发布时间】: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>

【问题讨论】:

    标签: typescript vue.js vuejs2 vue-router vue-class-components


    【解决方案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的默认值
    猜你喜欢
    • 2019-06-11
    • 2020-02-09
    • 2017-12-13
    • 2018-05-25
    • 1970-01-01
    • 2019-09-04
    • 2020-04-17
    • 2016-10-22
    相关资源
    最近更新 更多