【问题标题】:Mutating local properties in Vue / Nuxt (typescript)在 Vue / Nuxt(打字稿)中改变本地属性
【发布时间】:2018-07-28 11:30:57
【问题描述】:

我想要一个属性showLogo,当我调用方法hideLogo()时可以设置为false

import Component from 'nuxt-class-component'
import Vue from 'vue'
import { Prop } from 'vue-property-decorator'
import Logo from '~/components/Logo.vue'

@Component({
  components: {
    Logo
  }
})

export default class extends Vue {
  @Prop({ default: true })
  showLogo: boolean

  hideLogo(): void {
    this.showLogo = false
  }
}

这会产生警告: [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "showLogo"

执行此任务的正确方法是什么?

【问题讨论】:

  • @yuriy636 我可能会误解文档,但是当您有子组件引用和改变其父组件属性时,问题就会出现,这与状态更改的向下流动相反。我的组件没有任何子组件,并且正在使用自己的方法 hideLogo() 修改自己的属性 showLogo -- 没有其他组件引用 showLogo,因此数据流是自包含的。
  • showLogo 不是您的组件从父级接收的道具吗?或者即使没有通过,它仍然是一个 prop 并且 Vue 仍然会触发警告。
  • @yuriy636 showLogo 由同一组件中定义的事件触发。

标签: typescript vue.js vue-component nuxt.js


【解决方案1】:

错误输出给你一个很好的提示。你永远不应该直接从组件内部改变 props。道具意味着只能由模板中的父组件访问,如下所示:

<template>
  <your-component :show-logo="true">
<template>

如果您希望在组件内部具有可变的值,请按照错误提示执行操作:“相反,请使用基于 prop 值的数据或计算属性。” p>

由于您使用的是打字稿,因此您的数据应如下所示:

export default class extends Vue {
  showLogo: boolean = true

  hideLogo(): void {
    this.showLogo = false
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-13
    • 2021-08-21
    • 2019-02-06
    • 2021-01-20
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 2021-09-23
    相关资源
    最近更新 更多