Vue.js子組件向父組件通信的方法實例代碼詳解
一、場景描述:
曾經(jīng)有個電商項目,其中有個“老帶新”模塊,而且該模塊新增的入口很多,但是新增后展示效果還不一樣,當時就考慮將新增的組件單獨拿出來,其實就是一個子組件向父組同步數(shù)據(jù)的過程。
當然,背景不重要了,關(guān)鍵是看實現(xiàn)的方式。
二、場景展示效果
(PS:展示效果請忽略美感)
三、如何實現(xiàn)
注意:Vuejs架構(gòu)通過vue-cli 3.X搭建的項目,版本無所謂。
1、先看下目錄體系,下圖子組件放在components文件夾內(nèi),模擬子組件為itemAdd.vue,父組件視圖放在views文件夾內(nèi),模擬父組件名稱為Home.vue。
2、效果圖里面可以看出有兩個三個元素:輸入框、單選框、和新增按鈕。
輸入框使用v-model綁定值,方便后邊獲取到輸入框數(shù)值; 單選框同樣使用v-model綁定值,在新增時,將picked的值同步至父組件; 新增按鈕,新增時將表單元素的組件值,操作傳遞事件;
子組件元素代碼:
<template> <div class='add_item'> <label for="username">用戶名: <input id='username' v-model='username' type="text" name='name'> </label> <span>username:{{username}}</span> <br /> <input type="radio" value='男' id='male' v-model='picked'> <label for="male">男</label> <input type="radio" value='女' id='female' v-model='picked'> <label for="female">女</label> <span>picked:{{picked}}</span> <br /> <button @click='add_user'>新增</button> </div> </template>
子組件數(shù)據(jù)、事件均放在script里面:
<script> export default { name: "itemadd", data() { return { username: "", picked: '男' } }, methods: { add_user() { let user={username:this.username,sex:this.picked} this.$emit('adduser',user) } } } </script>
順便貼下子組件的樣式
<style> .add_item { width: 100%; background-color: lightblue; padding-top: 10px; padding-bottom: 10px; } .add_item button { outline: none; border: none; width: 200px; height: 40px; color: white; background-color: green; border-radius: 10px; } </style>
3、父組件在使用子組件時,先獲取到子組件,一并在代碼里面展示組件事件
父組件的script內(nèi),獲取子組件、初始列表數(shù)據(jù)、以及組件數(shù)據(jù)傳遞方法,代碼有簡單說明
<script> // 獲取組件 import itemAdd from '@/components/itemAdd.vue' export default { name: 'home', data() { return { // 設置初始列表值,為展示效果,特意初始一條數(shù)據(jù) userList: [{ username: "yang", sex: "男" }] } }, methods: { //調(diào)用子組件時添加數(shù)據(jù)到父組件數(shù)據(jù) newuser(user) { this.userList.push(user) } }, //子組件調(diào)用 components: { itemAdd } } </script>
父組件通過v-on,添加事件方法
<template> <div class="home"> <!-- 子組件調(diào)用,并添加時間方法 --> <item-add @adduser='newuser'></item-add> <ul> <!-- 簡單的樣式展示 --> <li> <span>用戶名</span> <span>性別</span> </li> <li v-for='user in userList' :key='user.id'> <span>{{user.username}}</span> <span>{{user.sex}}</span> </li> </ul> </div> </template>
按照流程,隨便貼下父組件樣式
<style scoped> li { list-style: none; } li:nth-child(even) { background-color: lightgrey; } </style>
四、總結(jié):
子組件通過事件向父組件同部數(shù)據(jù),上文展示的是通過$emit事件。其實還有v-model、Vuex等方式進行傳遞數(shù)據(jù)。
以上所述是小編給大家介紹的Vue.js子組件向父組件通信的方法實例代碼詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
vue實現(xiàn)動態(tài)表格提交參數(shù)動態(tài)生成控件的操作
這篇文章主要介紹了vue實現(xiàn)動態(tài)表格提交參數(shù)動態(tài)生成控件的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11Vue+Element+Springboot圖片上傳的實現(xiàn)示例
最近在學習前段后分離,本文介紹了Vue+Element+Springboot圖片上傳的實現(xiàn)示例,具有一定的參考價值,感興趣的可以了解一下2021-11-11淺談vue項目重構(gòu)技術(shù)要點和總結(jié)
這篇文章主要介紹了淺談vue項目重構(gòu)技術(shù)要點和總結(jié),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01