【问题标题】:"Property or method "foo" is not defined on the instance but referenced during render" Vuejs Typescript“属性或方法“foo”未在实例上定义,但在渲染期间引用”Vuejs Typescript
【发布时间】:2019-03-30 21:18:22
【问题描述】:

实例上未定义属性或方法“foo” 但在渲染期间引用。确保此属性是 反应式,无论是在数据选项中,还是对于基于类的组件,通过 初始化属性。

我曾使用过 vuejs,现在我正在转向 typescript,因为我试图访问一个简单的属性并使其具有响应性。

已提出类似问题,但尚未解决: Vue Class Based Component Warning: Property is not defined on the instance but referenced during render

<template>
    <section class="dropdown" style="background-color: #dde0e3">
      <select class="btnList" v-model="foo">
        <option v-for="item in selectedfooData" :value="item" :key="item.id">{{item}}</option>
      </select>
      {{foo}}
    </section>
</template>

<script lang="ts">
 import { Component, Prop, Vue } from 'vue-property-decorator';
 @Component
 export default class HelloWorld extends Vue {  
   private foo: string;
     private selectedfooData : string[] = [
     'one',
     'two'
     ]
 }
</script>

我已尝试通过将属性添加为道具来解决此问题,但这给了我错误提示,那么尝试这个的正确方法是什么?

避免直接改变prop,因为值会被覆盖 每当父组件重新渲染时。相反,使用数据或 基于道具值的计算属性。道具被变异: “富”

 @prop()
 private foo: string;

【问题讨论】:

  • 你尝试在 vue 的 data 对象中添加 foo 吗?
  • 这是class based 方法,所以存在no data object,我们需要定义一个构造函数。 @Capt.Teemo

标签: typescript vue.js v-model


【解决方案1】:

这里是解决这个问题的方法,需要添加一个构造函数并在构造函数中初始化属性

<template>
<section class="dropdown" style="background-color: #dde0e3">
  <select class="btnList" v-model="foo">
    <option v-for="item in selectedfooData" :value="item" :key="item.id">{{item}}</option>
    </select>
    {{foo}}
  </section>
</template>

<script lang="ts">
  import { Component, Prop, Vue } from 'vue-property-decorator';
  @Component
  export default class HelloWorld extends Vue {  
  private foo: string;
  private selectedfooData : string[] = [
   'one',
   'two'
  ]
  construtor() { 
    super();
    this.foo = '';
  }

 }
</script>

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 2019-08-08
    • 2018-07-13
    • 1970-01-01
    • 2020-07-07
    • 2019-06-25
    • 2017-06-16
    • 2018-06-22
    • 2020-09-02
    相关资源
    最近更新 更多