Vue2.0父元件向子元件傳值,動態修改資料問題[props導致的問題]
阿新 • • 發佈:2018-12-21
在Vue2.0中,專案開發時遇到的問題。
在子元件定義
<script> export default { props:['displaySelf'] } </script>
在父元件呼叫子元件並對displaySelf賦值後,在點選按鈕進行動態修改值時問題來了。
Avoid mutating a prop directly since the value will be
overwritten whenever the parent component re-
由於在vue2.0中作了修改,props只能單向傳值,如果該值時動態的且在子元件對該值作了處理就會導致問題發生。因為vue元件是相對獨立體,Props裡的值是被認為是“不可改變的”,當你去做更改時就會出問題。
搞清楚問題之後,那我們就好改了。這裡直接拋棄原來的做法,只需要在你的父元件初始化呼叫時新增“ref”並呼叫即可。
初始化子元件呼叫:
<StationsLinesWindow
ref="StationsLinesWindow"
</StationsLinesWindow>
父元件methods中通過“that.$refs.宣告的子元件名.子元件中對應的方法名”來呼叫子元件方法:
methods:{ drawing(){ var that = this; that.$refs.StationsLinesWindow.closePanel("close-button"); }, }
子元件StationsLinesWindow中:
methods:{ closePanel(type){ if(type == "close-button"){ this.$confirm('關閉視窗將不會上傳您新增或修改的資料,請確認是否已上傳,是否繼續?','提示',{ confirmButtonText: '確認關閉', cancelButtonText: '取消', type: 'warning' }).then(()=>{ this.displaySelf = false; }).catch(()=>{}); } }, }
測試無問題。