【vue】父子元件通訊遇到的錯誤資訊
阿新 • • 發佈:2020-09-09
大意:
父元件控制子元件Dialog 對話方塊的顯隱
錯誤demo:
父元件:
<template> <div class="app-container "> <my-sun-component :is-show="isShow"></my-sun-component> <el-button type="text" @click.native="handleButton">點選開啟Dialog</el-button> </div> </template><script> import mySunComponent from '@/views/skill/csun.vue'; export default { components: {mySunComponent}, data() { return { isShow: false, } }, created(){ }, methods: { handleButton(){this.isShow = true; } }, } </script>
子元件
<template> <div class="app-container"> <el-dialog title="提示" :visible.sync="isShow" width="30%"> <span>這是一段資訊</span> <span slot="footer" class="dialog-footer"> <el-button @click="isShow = false">取 消</el-button> <el-button type="primary" @click="isShow = false">確 定</el-button> </span> </el-dialog> </div> </template> <script> export default { name:'mySunComponent', data() { return { } }, created(){ }, props:{ isShow:{ type: Boolean, default: function(){ return false } } }, methods: { }, } </script>
頁面效果:
錯誤截圖:
錯誤文字版:
[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: "isShow"
解決方案:
父元件:
<template> <div class="app-container "> <my-sun-component :is-show="isShow"></my-sun-component> <el-button type="text" @click.native="handleButton">點選開啟Dialog</el-button> </div> </template> <script> import mySunComponent from '@/views/skill/csun.vue'; export default { components: {mySunComponent}, data() { return { isShow: 0, } }, created(){ }, methods: { handleButton(){ this.isShow = Math.random()*10 + 1; } }, } </script>
子元件
<!-- des:子元件 --> <template> <div class="app-container"> <el-dialog title="提示" :visible.sync="isVisible" width="30%"> <span>這是一段資訊</span> <span slot="footer" class="dialog-footer"> <el-button @click="isVisible = false">取 消</el-button> <el-button type="primary" @click="isVisible = false">確 定</el-button> </span> </el-dialog> </div> </template> <script> export default { name:'mySunComponent', data() { return { isVisible: false, } }, created(){ }, watch: { isShow(val){ this.isVisible = val ? true : false } }, props:{ isShow:{ type: Number, default: function(){ return 0 } } }, methods: { }, } </script>
ps:
- 在父元件時這樣寫this.isShow = Math.random()*10 + 1; 是因為watch監控的值只有變化的時候才能監聽到
- isVisible:this.isVisible 不可以這樣寫,因為會報如下錯誤(在demo中未報錯,在專案使用中報錯了,待解析)
錯誤文案:
[Vue warn]: Invalid prop: type check failed for prop "visible". Expected Boolean, got Number with value 0.