避免直接更改道具,因为值会被覆盖 [英] Avoid mutating a prop directly since the value will be overwritten

查看:478
本文介绍了避免直接更改道具,因为值会被覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在升级到Vue 2.0时遇到了一个非常普遍的问题

I have very common problem with upgrading to 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 )

我阅读了很多次文档,但仍然不知道如何解决.

I read the documentation many times but I still can't understand how to fix it.

usernamepassword.

这是我的代码:

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,但是它似乎没有用,而且我不明白为什么.它将值绑定到父项(主Vue应用)

I tried v-bind but it does not seem to work, and I can't understand why. It should bind the value to parent (the main Vue app)

推荐答案

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

From Vue 2.3.0 on you can use the .sync modifier:

来自 https://vuejs.org/v2/的示例guide/components-custom-events.html#sync-Modifier :

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

并在您的控制器中...

and in your controller...

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

这篇关于避免直接更改道具,因为值会被覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆