vuejs父子組件之間數(shù)據(jù)交互詳解
父子組件之間的數(shù)據(jù)交互遵循:
props down - 子組件通過props接受父組件的數(shù)據(jù)
events up - 父組件監(jiān)聽子組件$emit的事件來操作數(shù)據(jù)
示例
子組件的點擊事件函數(shù)中$emit自定義事件
export default {
name: 'comment',
props: ['issue','index'],
data () {
return {
comment: '',
}
},
components: {},
methods: {
removeComment: function(index,cindex) {
this.$emit('removeComment', {index:index, cindex:cindex});
},
saveComment: function(index) {
this.$emit('saveComment', {index: index, comment: this.comment});
this.comment="";
}
},
//hook
created: function () {
//get init data
}
}
父組件監(jiān)聽事件
父組件的methods中定義了事件處理程序
removeComment: function(data) {
var index = data.index, cindex = data.cindex;
var issue = this.issue_list[index];
var comment = issue.comments[cindex];
axios.get('comment/delete/cid/'+comment.cid)
.then(function (resp) {
issue.comments.splice(cindex,1);
});
},
saveComment: function(data) {
var index = data.index;
var comment = data.comment;
var that = this;
var issue =that.issue_list[index];
var data = {
iid: issue.issue_id,
content: comment
};
axios.post('comment/save/',data)
.then(function (resp) {
issue.comments=issue.comments||[];
issue.comments.push({
cid: resp.data,
content: comment
});
});
//clear comment input
this.comment="";
}
},
注意參數(shù)的傳遞是一個對象
其實還有更多的場景需要組件間通信
官方推薦的通信方式
- 首選使用Vuex
- 使用事件總線:eventBus,允許組件自由交流
- 具體可見:$dispatch 和 $broadcast替換
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Vite模塊動態(tài)導(dǎo)入之Glob導(dǎo)入實踐
import.meta.glob是Vite提供的強大模塊動態(tài)導(dǎo)入功能,用于在構(gòu)建時批量導(dǎo)入模塊并生成按需加載的代碼,適用于處理大量文件2026-01-01
Vue3+antDesignVue實現(xiàn)表單校驗的方法
這篇文章主要為大家詳細介紹了基于Vue3和antDesignVue實現(xiàn)表單校驗的方法,文中的示例代碼講解詳細,具有一定的參考價值,需要的小伙伴可以了解下2024-01-01
vue3.2+ts實現(xiàn)在方法中可調(diào)用的擬態(tài)框彈窗(類el-MessageBox)
這篇文章主要介紹了vue3.2+ts實現(xiàn)在方法中可調(diào)用的擬態(tài)框彈窗(類el-MessageBox),這個需求最主要的是要通過方法去調(diào)用,為了像el-messagebox使用那樣方便,需要的朋友可以參考下2022-12-12
vue子組件使用自定義事件向父組件傳遞數(shù)據(jù)
這篇文章主要介紹了vue子組件使用自定義事件向父組件傳遞數(shù)據(jù)的方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-05-05
vue 3 中watch 和watchEffect 的新用法
本篇文章主要通過 Options API 和 Composition API 對比 watch 的使用方法,讓大家快速掌握 vue3 中 watch 新用法,需要的朋友可以參考一下哦,希望對大家有所幫助2021-11-11
Vue中的數(shù)據(jù)監(jiān)聽和數(shù)據(jù)交互案例解析
這篇文章主要介紹了Vue中的數(shù)據(jù)監(jiān)聽和數(shù)據(jù)交互案例解析,在文章開頭部分先給大家介紹了vue中的數(shù)據(jù)監(jiān)聽事件$watch,具體代碼講解,大家可以參考下本文2017-07-07
在IDEA?2024創(chuàng)建Vue項目的完整實例代碼
Vue.js是一個構(gòu)建用戶界面的漸進式框架,而IntelliJ IDEA是一款功能強大的Java集成開發(fā)環(huán)境(IDE),但它也支持多種前端技術(shù),包括Vue.js,這篇文章主要介紹了在IDEA 2024創(chuàng)建Vue項目的相關(guān)資料,需要的朋友可以參考下2026-02-02

