【问题标题】:VueJS warning Avoid mutating a prop directlyVueJS 警告避免直接改变道具
【发布时间】:2019-02-07 15:33:06
【问题描述】:

当我尝试使用 @click 指令更改道具的值时收到此警告:

[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: "name"

我的代码如下:

<html>
<head>
<title>Vue test</title>
</head>
<body>
<div id="app">
    <user-name name="Flavio"></user-name>

</div>

<script src="assets/js/vue.js"></script>
<script type="text/javascript">
    Vue.component('user-name', {

      props: ['name'],
      template: '<p @click=bio1()>Hi {{ name }}</p>',

      methods: {
        bio1(){
            this.name = "Caleb";
        }
      }
    })

    new Vue({
      el: "#app"
    })
</script>

</body>
</html>

这个警告的原因是什么?

【问题讨论】:

标签: javascript vue.js vuejs2 vue-component vue-reactivity


【解决方案1】:

VueJS 中的props 形成单向数据绑定。这意味着,您将 props 中的值从父组件传递给子组件,并避免子组件改变这些属性。每次更新父组件时,更新的值也会在子组件中刷新。

在您的情况下,由于您需要更新传递下来的道具的值,因此最好使用道具的值定义计算属性:

props: ['name'],
computed: {
  localizedName: function () {
    return this.name.trim()
  }
}

详细了解 VueJS 中的单向数据流:https://vuejs.org/v2/guide/components-props.html#One-Way-Data-Flow

【讨论】:

    猜你喜欢
    • 2018-03-05
    • 2020-06-23
    • 2018-08-25
    • 2021-06-18
    • 2019-11-07
    • 2020-12-23
    • 2020-09-11
    • 2019-09-11
    • 1970-01-01
    相关资源
    最近更新 更多