Vue 进阶组件实战应用 -- 父子组件传值的应用实例(子父组件传值的两种触发方式)
生活随笔
收集整理的這篇文章主要介紹了
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 进阶组件实战应用 -- 父子组件传值的应用实例(子父组件传值的两种触发方式)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Idea 创建简单的SpringBoot
- 下一篇: 我的世界minecraft-Python