javascript - 避免直接修改 prop,因为值会被覆盖

标签 javascript vue.js

我在升级到 Vue 2.0 时遇到了一个很常见的问题

我收到警告:

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: "username" (found in the component )

我看了很多次文档,但我仍然不明白如何修复它。

usernamepassword 在主 Vue 应用程序中声明。

这是我的代码:

var GuestMenu = Vue.extend({
   props : ['username', 'password'],
      template: `
        <div id="auth">
            <form class="form-inline pull-right">
                <div class="form-group">
                    <label class="sr-only" for="UserName">User name</label>
                  <input type="username" v-model="username" class="form-control" id="UserName" placeholder="username">
                </div>
                <div class="form-group">
                  <label class="sr-only" for="Password">Password</label>
                  <input type="password" v-model="password" class="form-control" id="Password" placeholder="Password">
                </div>
            </form>
        </div>`,
    });

App = new Vue ({ 
   el: '#app',
  data: 
    {
      topMenuView: "guestmenu",
      contentView: "guestcontent",
      username: "",
      password: "",

    }
})

我试过 v-bind 但它似乎不起作用,我不明白为什么。它应该将值绑定(bind)到父级(主要 Vue 应用程序)

最佳答案

从 Vue 2.3.0 开始,您可以使用 .sync 修饰符:

样本来自 https://v2.vuejs.org/v2/guide/components-custom-events.html#sync-Modifier :

<text-document :title.sync="title"></text-document>

在你的 Controller 中......

this.$emit('update:title', newTitle)

关于javascript - 避免直接修改 prop,因为值会被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40574661/

相关文章:

javascript - 从 1 个 Eloquent 模型 - Vue - Laravel 将数组和数据插入表和交叉表

javascript - 查看输出不显示

javascript - 单击超链接时如何将 href 值传递给 javascript 并在 window.location 中使用它?

javascript - 如何以 Angular 选择按钮

javascript - 如何在每个动态创建的图像下方显示一个数字?

javascript - 使用 Vue.js 为恒定(未知)数据流设置动画的最佳方式?

vue.js - 无法将国际化插件 i18n 与 Pinia Store 一起使用

vue.js - Vuetify - 在 v-list-tile-content 中居中内容

javascript - 如何通过更改宽度并在其中插入图标​​来设置 vue-bootstrap-datetimepicker 的样式?

javascript - 有没有办法获取函数表达式的构造函数名称?