詳解Vue之父子組件傳值
一、簡要介紹
父子組件之間的傳值主要有三種:傳遞數(shù)值、傳遞方法、傳遞對象,主要是靠子組件的 props 屬性來接收傳值,下面分別介紹:
(一)傳遞數(shù)值
1.子組件:Header.vue
<template> <div> <!-- data對象里并沒有 msg 屬性,這里調(diào)用的是父類傳遞過來的 msg 屬性 --> <h2>{{msg}}</h2> </div> </template> <script> export default { data() { return { } }, methods: { }, // 接收父類的傳值 props: ['msg'] } </script>
可以看到,在子組件中的data對象里并沒有 msg 屬性,這里調(diào)用的是父類傳遞過來的 msg 屬性,接收就是靠 props: ['msg']。
2.父組件Home.vue
<template> <div> <!-- 2.使用子組件,并向子組件傳值 --> <v-head :msg="msg"></v-head> <br> <br> </div> </template> <script> // 1.引入子組件 import Head from './Head.vue'; export default { data() { return { msg: '我是一個組件' } }, methods: { }, components: { "v-head": Head }, // 頁面刷新時請求數(shù)據(jù) mounted() { } } </script>
傳值的核心思想就是,在使用子組件的地方,加上要傳遞的值:<v-head :msg="msg"></v-head>
(二)傳遞方法
傳遞方法的寫法和傳遞數(shù)值一樣,下面只寫出關(guān)鍵步驟:
父組件
<template> <div> <!-- 2.使用子組件,并向子組件傳值 --> <v-head :run="run"></v-head> <br> <br> </div> </template> <script> // 1.引入子組件 import Head from './Head.vue'; export default { data() { return { msg: '我是一個組件' } }, methods: { run() { alert(this.msg); } }, components: { "v-head": Head }, // 頁面刷新時請求數(shù)據(jù) mounted() { } } </script>
子組件
<template> <div> <button @click="run">接收父組件的方法</button> </div> </template> <script> export default { data() { return { } }, methods: { }, // 接收父類的傳值 props: ['run'] } </script>
(三)傳遞對象
傳遞對象的寫法和傳遞數(shù)值一樣,下面只寫出關(guān)鍵步驟:
父組件
<template> <div> <!-- 2.使用子組件,并向子組件傳值,這里的 this 就是 Home 組件 --> <v-head :home="this"></v-head> <br> <br> </div> </template> <script> // 1.引入子組件 import Head from './Head.vue'; export default { data() { return { msg: '我是一個組件' } }, methods: { run() { alert(this.msg); } }, components: { "v-head": Head }, // 頁面刷新時請求數(shù)據(jù) mounted() { } } </script>
子組件
<template> <div> <!-- data對象里并沒有 msg 屬性,這里調(diào)用的是父類傳遞過來的 msg 屬性 --> <h2>{{msg}}</h2> <br> <br> <button @click="run">接收父組件的方法</button> </div> </template> <script> export default { data() { return { // 調(diào)用傳過來的home組件的msg屬性 msg: this.home.msg } }, methods: { run() { // 調(diào)用傳過來的home組件的run()方法 this.home.run(); } }, // 接收父類的傳值 props: ['home'] } </script>
(四)傳遞數(shù)值類型校驗
props: { 'home': Object }
其他和上面類似!
以上所述是小編給大家介紹的Vue之父子組件傳值詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
Vue源碼解析之?dāng)?shù)組變異的實現(xiàn)
這篇文章主要介紹了Vue源碼解析之?dāng)?shù)組變異的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-12-12使用Element時默認勾選表格toggleRowSelection方式
這篇文章主要介紹了使用Element時默認勾選表格toggleRowSelection方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10Vue中ElementUI結(jié)合transform使用時彈框定位不準(zhǔn)確問題解析
在近期開發(fā)中,需要將1920*1080放到更大像素大屏上演示,所以需要使用到transform來對頁面進行縮放,但是此時發(fā)現(xiàn)彈框定位出錯問題,無法準(zhǔn)備定位到實際位置,本文給大家分享Vue中ElementUI結(jié)合transform使用時彈框定位不準(zhǔn)確解決方法,感興趣的朋友一起看看吧2024-01-01