新聞中心
這篇文章給大家分享的是有關(guān)vue中如何實現(xiàn)讓子組件修改父組件數(shù)據(jù)的方法的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考。一起跟隨小編過來看看吧。
一、關(guān)于vue中watch的認識
我們要監(jiān)聽一個屬性的的變化就使用watch一般是父組件傳遞給子組件的時候
?1、常見的使用場景
... watch:{ value(val) { console.log(val); this.visible = val; } } ...
相關(guān)學習推薦:javascript視頻教程
?2、如果要一開始就執(zhí)行
... watch: { firstName: { handler(newName, oldName) { this.fullName = newName + '-' + this.lastName; }, immediate: true, } } ...
?3、深度監(jiān)聽(數(shù)組、對象)
... watch: { obj: { handler(newName, oldName) { console.log('///') }, immediate: true, deep: true, } ...
二、關(guān)于子組件修改父組件屬性認識
在vue2.0+ 后不再是雙向綁定,如果要進行雙向綁定需要特殊處理。
[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: "你修改的屬性名"
?1、通過事件發(fā)送給父組件來修改
**在子組件test1中**{{item}}
... methods: { add() { // 直接把數(shù)據(jù)發(fā)送給父組件 this.$emit('update', this.book); this.book = ''; }, }, **在父組件中**... addBook(val) { this.books = new Array(val) },
?2、使用.sync 來讓子組件修改父組件的值(其實是上面方法的精簡版)
**在父組件中,直接在需要傳遞的屬性后面加上.sync****在子組件中**
{{word}}
?3、在子組件中拷貝一份副本
**子組件中** export default { props: { // 已經(jīng)選中的 checkModalGroup: { type: Array, default: [], required: false, } }, data() { return{ copyCheckModalGroup: this.checkModalGroup, // 選中的 } }, methods: { // 一個一個的選擇 checkAllGroupChange(data) { // 把當前的發(fā)送給父組件 this.$emit('updata', data); }, }, watch: { checkModalGroup(newVal, oldVal) { this.copyCheckModalGroup = newVal; } } } **父組件中直接更新傳遞給子組件的數(shù)據(jù)就可以** ... // 更新子組件數(shù)據(jù) roleCheckUpdata(data) { this.roleGroup = data; }, ...
感謝各位的閱讀!關(guān)于vue中如何實現(xiàn)讓子組件修改父組件數(shù)據(jù)的方法就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
文章題目:vue中如何實現(xiàn)讓子組件修改父組件數(shù)據(jù)的方法-創(chuàng)新互聯(lián)
文章分享:http://www.dlmjj.cn/article/dehiid.html