詳解vue中父子組件傳遞參數(shù)props的實現(xiàn)方式
更新時間:2023年07月30日 09:42:16 作者:tommoq
這篇文章主要給大家介紹了在vue中,父子組件傳遞參數(shù)?props?實現(xiàn)方式,文章通過代碼示例介紹的非常詳細,對我們的學習或工作有一定的參考價值,需要的朋友可以參考下
通過 Prop 向子組件傳遞數(shù)據(jù)
001:父組件=====》子組件通信
<template> <div> <h1>這里是父元素</h1> //****** <childComponent :detailMes="detailMes"/> </div> </template> <script> import childComponent from './childComponent' export default { name:"parentComponent", data() { return { detailMes:'111' } }, components: { childComponent, }, } </script>
子組件
<template> <div> 數(shù)據(jù)需要從父元素傳遞過來哦:{{detailMes}} </div> </template> <script> export default { name:'childComponent', data() { return { } }, props: { detailMes:{ type : String, } }, methods: { name() { } } }
002:子組件=====》父組件通信
(要求父組件先給子組件一個函數(shù))
列表數(shù)據(jù)在父組件,循環(huán)的ul>li在子組件,現(xiàn)在在組件刪除數(shù)據(jù),需要通知父組件
<template> <div> <h1>這里是父</h1> //父組件先給子組件一個函數(shù) <childComponent :list="list" :del="del"/> </div> </template> <script> import childComponent from './childComponent' export default { data() { return { list:[ {id:"001",stuName:'學生a'}, {id:"002",stuName:'學生b'}, ] } }, components: { childComponent, }, methods: { del(id) { const idx=this.list.findIndex(v=>v.id==id); if(idx>-1){ this.list.splice(idx,1) } // this.list=this.list.filter(item=>item.id!==id) } }, } </script>
<template> <div> 子組件 <ul> <li v-for="item of list" :key="item.id"> <span>{{item.stuName}}</span> <button @click="dele(item.id)" class="red">x</button> </li> </ul> </div> </template> <script> export default { name:'childComponent', data() { return { } }, props: { // 父元素傳遞過來的方法 list:{}, // 父組件傳遞過來的方法 del:{} }, methods: { dele(ids) { // 通知父元素,快刪除數(shù)據(jù)了 // 去調(diào)用父組件的方法 this.del(ids); } } }
003 傳遞 多層傳遞下去
<template> <div> <h1>這里是父</h1> <childComponent :msg="msg"/> </div> </template> <script> import childComponent from './childComponent' export default { data() { return { msg:'這條數(shù)據(jù)需要通過層層傳遞下去' } }, components: { childComponent, }, } </script>
<template> <div> 子組件 <grandsonComponent :msg="msg"></grandsonComponent> </div> </template> <script> import grandsonComponent from '@/components/grandsonComponent.vue'; export default { components: { grandsonComponent, }, props: { msg:{} }, } </script>
<template> <div> 這是統(tǒng)計的{{msg}}的數(shù)據(jù) </div> </template> <script> export default { name:'grandsonComponent', props: { msg: {} }, } </script>
到此這篇關于詳解vue中父子組件傳遞參數(shù)props實現(xiàn)方式的文章就介紹到這了,更多相關vue父子組件傳遞props內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue + vuex todolist的實現(xiàn)示例代碼
這篇文章主要介紹了vue + vuex todolist的實現(xiàn)示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03