vue.esm.js?efeb:628 [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: "data"
found in
---> <Son> at src/vue/components/son.vue <App> at src/vue/App.vue <Root>
原因分析:
父组件传参给子组件的prop属性,这是单向绑定
但是在子组件中修改了prop属性,就导致了这种报错
可以看下代码
App.vue
<template> <son :data="data" /> </template> <script> import son from "./components/son"; export default { components: { son }, data() { return { data: 1 }; } }; </script>
son.vue
<template> <input type="text" v-model="data" /> </template> <script> export default { data() { return {}; }, props: ["data"] }; </script>
解决办法:
用一个副本变量来替代prop,上代码
只需要修改son.vue
<template> <input type="text" v-model="myData" /> </template> <script> export default { data() { return { myData: null }; }, props: ["data"], created() { this.myData = this.data; } }; </script>