VueJS警告避免直接改变道具

时间:2018-09-02 08:08:13

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

当我尝试使用@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>

此警告的原因是什么?

1 个答案:

答案 0 :(得分:2)

VueJS中的if(!double.TryParse(tb_credit.Text, out var creditHours)) { throw new Exception("Credit hours should be a numbers between 0 and 6."); } if (creditHours > 0 || creditHours < 6) { creditHours = double.Parse(tb_credit.Text); } throw new Exception("Credit hours should be a numbers between 0 and 6.") 构成单向数据绑定。意思是,您将props中的值从父级传递给子级组件,并避免子级组件更改这些属性。每次更新父组件时,更新的值也会在子组件中刷新。

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

props

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