Vue1.0元件間傳遞
使用$on()監聽事件;
使用$emit()在它上面觸發事件;
使用$dispatch()派發事件,事件沿著父鏈冒泡;
使用$broadcast()廣播事件,事件向下傳導給所有的後代
Vue2.0後$dispatch(),$broadcast()被棄用,請參閱https://cn.vuejs.org/v2/guide/migration.html#dispatch-和-broadcast-替換
1.子元件傳送值給父元件的:
Child.vue
<template> <p class="child"> <h1>子组件</h1> <button v-on:click="childToParent">想父组件传值</button> </p> </template> <script> export default{ name: 'child', data(){ return {} }, methods: { childToParent(){ this.$emit("childToParentMsg", "子组件向父组件传值"); } } } </script>parent.vue
<template> <p class="parent"> <h1>父组件</h1> <Child v-on:childToParentMsg="showChildToParentMsg" ></Child> </p> </template> <script> import Child from './child/Child.vue' export default{ name:"parent", data(){ return { } }, methods: { showChildToParentMsg:function(data){ alert("父组件显示信息:"+data) } }, components: {Child} } </script>
2.父元件傳值給子元件
parent.vue
<template> <p class="parent"> <h1>父组件</h1> <Child v-bind:parentToChild="parentMsg"></Child> </p> </template> <script> import Child from './child/Child.vue' export default{ name:"parent", data(){ return { parentMsg:'父组件向子组件传值' } }, components: {Child} } </script>
child.vue
#<template> <p class="child"> <h1>子组件</h1> <span>子组件显示信息:{{parentToChild}}</span><br> </p> </template> <script> export default{ name: 'child', data(){ return {} }, props:["parentToChild"] } </script>
3.採用eventBus.js傳值---兄弟元件間的傳值
eventBus.js
import Vue from 'Vue' export default new Vue()
App.vue
<template> <p id="app"> <secondChild></secondChild> <firstChild></firstChild> </p> </template> <script> import FirstChild from './components/FirstChild' import SecondChild from './components/SecondChild' export default { name: 'app', components: { FirstChild, SecondChild, } } </script>
FirstChild.vue
#<template> <p class="firstChild"> <input type="text" placeholder="请输入文字" v-model="message"> <button @click="showMessage">向组件传值</button> <br> <span>{{message}}</span> </p> </template> <script> import bus from '../assets/eventBus'; export default{ name: 'firstChild', data () { return { message: '你好' } }, methods: { showMessage () { alert(this.message) bus.$emit('userDefinedEvent', this.message);//传值 } } } </script>
SecondChild.vue
#<template> <p id="SecondChild"> <h1>{{message}}</h1> </p> </template> <script> import bus from '../assets/eventBus'; export default{ name:'SecondChild', data(){ return { message: '' } }, mounted(){ var self = this; bus.$on('userDefinedEvent',function(message){ self.message = message;//接值 }); } }
以上是VUE2.0組件的傳值問題的詳細內容。更多資訊請關注PHP中文網其他相關文章!