Vue报错之"[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead......"

一.报错截图

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

 

 

 报错代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue组件</title>
</head>
<body>
    <div id="app">
        <!-- 自定义名:zinum,绑定数据模型:fuNum -->
        <wzwfuzi :zinum="fuNum"></wzwfuzi>
    </div>
    
</body>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
    // 父向子组件(将父组件的数据模型绑定到子组件的模板中,实现数据提供)
    // 自定义全局组件(子组件),注意这里改变的zinum值不会影响父组件的fuNum值
    Vue.component("wzwfuzi",{
        template:"<div>从父组件拿来的数据:{{zinum}}<button @click='zinum++'>点我加1==》{{zinum}}</button></div>",
        props:["zinum"], // 接受父组件传值[自定义名:zinum]
    })
    
    // 父组件:新建Vue
    const app = new Vue({
        el:"#app",
        data:{
            fuNum:5
        }
    })
</script>
</html>

 

二.分析的原因

  1. 由于Vue内部的机制,传入的props中的值
    是不允许被修改的。在新的渲染机制中,当父组件重新渲染时,子组件都被会覆盖,这时的props是不可变的。

  2. v2.6.10报错,而v2.5.17不报错

三.解决方案

  1. 在data中再定义两个新的变量,然后把父组件传过来的值赋值给新的变量,之后操作这两个新的变量即可。

 

posted @ 2021-08-18 15:44  骚哥  阅读(3306)  评论(0编辑  收藏  举报