日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

Vue 进阶组件实战应用 -- 父子组件传值的应用实例(子父组件传值的两种触发方式)

發布時間:2025/3/12 vue 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Vue 进阶组件实战应用 -- 父子组件传值的应用实例(子父组件传值的两种触发方式) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

基礎的子組件和父組件通信已經搞定了,可以看此博客 父子組件傳值基礎應用
需求
現在需求是在一個父頁面引用子組件,不只是要實現基本的父子組件傳值。并且子組件給父組件傳值的觸發條件要在父頁面觸發。

目前小編采用的方式是使用ref 屬性+this.emit 方法 ,在父頁面調用子頁面的方法結合this.emit方法實現。在父頁面調用子頁面的方法并且把子頁面里的值通過父頁面的自定義事件傳遞到父頁面。

注意:先新建子頁面,然后進行父子傳值,在父頁面注冊子頁面為組件

父->子傳值

父頁面

<template><div class="hello"><ChildComponents:msg="msgc"></ChildComponents><button @click="send()">向子組件傳值</button></div> </template><script> import ChildComponents from'./ChildComponents.vue' export default {name: 'HelloWorld',components: {'ChildComponents':ChildComponents},data () {return {msgc:''}},methods:{send(){this.msgc='來自HelloWorld父組件的值';}} } </script><!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> h3 {margin: 40px 0 0; } ul {list-style-type: none;padding: 0; } li {display: inline-block;margin: 0 10px; } a {color: #42b983; } </style>

子頁面

<template><div><div><h1>子組件的值</h1></div><div>{{msg}}<br/></div></div> </template><script>export default {name: 'test',components: {},props: {msg: String},data () {return {}} } </script> <style scoped></style>

結果:

子->父傳值

子頁面觸發

父頁面

<template><div class="hello"><ChildComponents@sendMsg="sendMsg":msg="msgc"></ChildComponents><h1>父組件的值</h1><br/>{{msgp}}<button @click="send()">向子組件傳值</button></div> </template><script> import ChildComponents from'./ChildComponents.vue' export default {name: 'HelloWorld',components: {'ChildComponents':ChildComponents},data () {return {msgc:'',msgp:'',}},methods:{sendMsg(data) {this.msgp=data;},send(){this.msgc='來自HelloWorld父組件的值';}} } </script><!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> h3 {margin: 40px 0 0; } ul {list-style-type: none;padding: 0; } li {display: inline-block;margin: 0 10px; } a {color: #42b983; } </style>

子頁面

<template><div><div><h1>子組件的值</h1></div><div>{{msg}}<br/><button @click="sendMsg()">向父組件傳值</button></div></div> </template><script>export default {name: 'test',components: {},props: {msg: String},data () {return {}},methods: {sendMsg() {//子頁面的值推送到父頁面的自定義事件里this.$emit('sendMsg',"來ChildComPonens自子組件的值")}}} </script> <style scoped></style>

結果:

父頁面觸發

父頁面需要修改的地方

<ChildComponents@sendMsg="sendMsg"ref="chile":msg="msgc"></ChildComponents><h1>父組件的值</h1><br/>{{msgp}}<button @click="sendParnt()">子組件向父組件傳值,父組件觸發</button>//增加一個方法methods:{sendParnt() {this.$refs.chile.sendmsgP()}}

子組件只需要增加一個方法 sendmsgP 父頁面可以通過ref 調用

methods: {sendMsg() {this.$emit('sendMsg',"來ChildComPonens自子組件的值")},sendmsgP(){this.sendMsg()}}

結果:

總結

以上是生活随笔為你收集整理的Vue 进阶组件实战应用 -- 父子组件传值的应用实例(子父组件传值的两种触发方式)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。