【问题标题】:props in components does not work interface - Nuxt and Vuejs组件中的道具不起作用界面 - Nuxt 和 Vuejs
【发布时间】:2022-01-15 06:33:14
【问题描述】:

我无法使用 props 在组件内处理对象的接口。

有谁知道我怎样才能让它工作?

Portaria接口

export interface PortariaInterface {
  dataEntrada: string
  nfe?: {
    numero: string
}

模板

<Formulario :formulario="formulario" />

Ts

import {PortariaInterface} from '@/models/PortariaInterface'
import { Formulario } from '@/components/portaria'

export default Vue.extend({
  name: 'IndexPage',
  components: { Formulario },
  layout: 'portaria',
  data() {
    return {
      formulario: {} as PortariaInterface
    }
  }
})

组件

<el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="4">
        <el-form-item label="Número NFe">
          <el-input v-model="formulario.nfe?.numero"></el-input>
        </el-form-item>
      </el-col>

export default Vue.extend({
  name: 'Formulario',
  props: ['formulario']
})

错误

TypeError: Cannot read properties of undefined (reading 'numero')

【问题讨论】:

    标签: typescript vue.js nuxt.js vuejs3


    【解决方案1】:

    在这种情况下,您有两个绑定,应该使用 v-model 指令在您的 Formulario 组件上完成,如下所示:

     <Formulario v-model="formulario" />
    

    在这个组件中使用value@input事件绑定输入:

    <el-col :xs="24" :sm="8" :md="8" :lg="6" :xl="4">
            <el-form-item label="Número NFe">
              <el-input :value="numero" @input="onInput"></el-input>
            </el-form-item>
          </el-col>
    
    export default Vue.extend({
      name: 'Formulario',
      props: ['value'],
      computed:{
       numero(){
         return this.value.nfe?.numero
       }
    
     },
     methods:{
      onInput(val){
        this.$emit('input',val)
      }
    }
    })
    
    

    【讨论】:

    • 该示例仅包含数字字段。但是还有更多的字段构成了 json 数据。例如:数字、日期、标题等。为每个输入字段创建一个组件不是一个好习惯。
    猜你喜欢
    • 2021-12-28
    • 1970-01-01
    • 2011-10-21
    • 2020-02-06
    • 2017-12-23
    • 2018-09-05
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    相关资源
    最近更新 更多