Vue组件之间相互传值的方式
生活随笔
收集整理的這篇文章主要介紹了
Vue组件之间相互传值的方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1父傳子
1.1父組件
1.2子組件:在 props 中添加了元素之后,就不需要在 data 中再添加變量了
?2子傳父
2.1子組件
2.2父組件
兄弟組件傳值一:使用全局函數全局事件
第一步: 在入口文件main.js里暴露一個vue實例
export const EventBus = new Vue() // 暴露一個vue實例第二步: 在要傳值的文件里導入vue實例模塊,age使用自己的變量,再定義一個全局觸發事件函數,觸發事件函數綁定在一個button上
<template><div><h3>用戶編輯頁面</h3><p>編輯用戶</p><p>年齡: {{ age }}</p><p><button @click="changeAge">編輯年齡</button></p></div> </template> <script> import { EventBus } from "../main.js" // 導入模塊 export default {// props: ["age"],data() {return {age: 10,}},methods: {changeAge: function() {this.age = 20EventBus.$emit("editAge", this.age)// 觸發全局事件 并且把改變后的值傳入事件函數// console.log(EventBus)}} } </script>第三步: 在要被傳入值得組件中也導入vue實例模塊,也不使用父組件中傳過來個age,自己重新定義,創建一個初始化的鉤子函數,再使用created鉤子函數中使用傳值組件的全局定義事件。
import { EventBus } from "../main.js" export default {data() {return {name : this.myName,age: 10}},methods: {changeParentName: function() {this.$emit('changeParentName', 'xiaohong')// this.$emit('')觸發自定義事件},created() {EventBus.$on('editAge', (age) => { // 使用$on去綁定事件this.age = age // 使用es6寫法,this剛好指向父級})} }?兄弟組件傳值二:使用全局函數全局事件
第一步: 在父組件中給要傳值的兄弟兩個都綁定要傳的變量。
<app-user-detail :age="age"></app-user-detail> <app-user-edit :age="age" @editAge="changeAge"></app-user-edit>第二步: 在要傳值得組件中接受變量和綁定觸發事件
<template><div><h3>用戶編輯頁面</h3><p>編輯用戶</p><p>年齡: {{ age }}</p><p><button @click="changeAge">編輯年齡</button></p></div> </template> <script> export default {props: ["age"],methods: {changeAge: function() {this.$emit('editAge', 20) // 觸發自定義事件并傳值}} } </script>第三步: 在父組件中綁定要傳組件中的自定義事件
export default {data() {return {name: 'zhuli',age: 10,}},components: {'app-user-detail': UserDetail,'app-user-edit': UserEdit,},methods: {changeAge: function(age) {this.age = age},} }總結: 當要傳值的組件改變了父組件的變量,父組件又可以把改變的值傳值所綁定變量的組件,實現兄弟間傳值。
總結
以上是生活随笔為你收集整理的Vue组件之间相互传值的方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 景宁水果批发市场在哪里?
- 下一篇: html5倒计时秒杀怎么做,vue 设