vue中如何讓子組件修改父組件數(shù)據(jù)
一、關(guān)于vue中watch的認識
我們要監(jiān)聽一個屬性的的變化就使用watch一般是父組件傳遞給子組件的時候
•1、常見的使用場景
... watch:{ value(val) { console.log(val); this.visible = val; } } ...
•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中** <input type="text" v-model="book"/> <button @click="add">添加</button> <p v-for="(item, index) of books" :key="index">{{item}}</p> ... methods: { add() { // 直接把數(shù)據(jù)發(fā)送給父組件 this.$emit('update', this.book); this.book = ''; }, }, **在父組件中** <test1 :books="books" @update="addBook"></test1> ... addBook(val) { this.books = new Array(val) },
•2、使用.sync 來讓子組件修改父組件的值(其實是上面方法的精簡版)
**在父組件中,直接在需要傳遞的屬性后面加上.sync** <test4 :word.sync="word"/> **在子組件中** <template> <div> <h3>{{word}}</h3> <input type="text" v-model="str" /> </div> </template> <script> export default { props: { word: { type: String, default: '', }, }, data() { return { str: '', } }, watch: { str(newVal, oldVal) { // 在監(jiān)聽你使用update事件來更新word,而在父組件不需要調(diào)用該函數(shù) this.$emit('update:word', newVal); } } } </script>
•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; }, ...
總結(jié)
以上所述是小編給大家介紹的vue中如何讓子組件修改父組件數(shù)據(jù),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
Vue報錯Module build failed: Error: Node&nb
這篇文章主要介紹了Vue報錯Module build failed: Error: Node Sass version 7.0.1 is incompatible with 4.0.0.解決方案,需要的朋友可以參考下2023-06-06vue前端開發(fā)輔助函數(shù)狀態(tài)管理詳解示例
vue的應用狀態(tài)管理提供了mapState、mapGetters、mapMutations、mapActions四個輔助函數(shù),所謂的輔助函數(shù)分別對State、Getters、Mutations、Actions在完成狀態(tài)的使用進行簡化2021-10-10Vue實現(xiàn)用戶沒有登陸時,訪問后自動跳轉(zhuǎn)登錄頁面的實現(xiàn)思路
這篇文章主要介紹了Vue實現(xiàn)用戶沒有登陸時,訪問后自動跳轉(zhuǎn)登錄頁面,定義路由的時候配置屬性,這里使用needLogin標記訪問頁面是否需要登錄,本文通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-02-02atom-design(Vue.js移動端組件庫)手勢組件使用教程
這篇文章主要介紹了atom-design(Vue.js移動端組件庫)手勢組件使用教程,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-05-05vue實現(xiàn)todolist基本功能以及數(shù)據(jù)存儲功能實例詳解
本文通過實例代碼給大家介紹了vue實現(xiàn)todolist基本功能以及數(shù)據(jù)存儲功能,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-04-04