1. 程式人生 > >vue2.0組件之間的傳值--新入坑,請指教

vue2.0組件之間的傳值--新入坑,請指教

fine ext sets mode tro exp ted pro -s

prop down emit up

嘿嘿 如果是第一次接觸vue2.0組件傳值的肯定很疑惑,這是什麽意思(大神總結的,我也就是拿來用用)

“down”—>指的是下的意思,即父組件向子組件傳值,用props;“up”—>指的是上的意思,即子組件想父組件傳值,用emit。

1.子組件向父組件的傳值:

Child.vue

<template>
<div class="child">
<h1>子組件</h1>
<button v-on:click="childToParent">想父組件傳值</button>
</div>
</template>
<script>
export default{
name: ‘child‘,
data(){
return {}
},
methods: {
childToParent(){
this.$emit
("childToParentMsg", "子組件向父組件傳值");
}
}
}
</script>

parent.vue
<template>
<div class="parent">
<h1>父組件</h1>
<Child v-on:childToParentMsg="showChildToParentMsg" ></Child>
</div>
</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>
<div class="parent">
<h1>父組件</h1>
<Child v-bind:parentToChild="parentMsg"></Child>
</div>
</template>
<script>
import Child from ‘./child/Child.vue‘
export default{
name:"parent",
data(){
return {
parentMsg:‘父組件向子組件傳值‘
}
},
components: {Child}
}
</script>

child.vue

<template>
<div class="child">
<h1>子組件</h1>
<span>子組件顯示信息:{{parentToChild}}</span><br>
</div>
</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>
<div id="app">
<secondChild></secondChild>
<firstChild></firstChild>
</div>
</template>

<script>
import FirstChild from ‘./components/FirstChild‘
import SecondChild from ‘./components/SecondChild‘

export default {
name: ‘app‘,
components: {
FirstChild,
SecondChild,
}
}
</script>

FirstChild.vue

<template>
<div class="firstChild">
<input type="text" placeholder="請輸入文字" v-model="message">
<button @click="showMessage">向組件傳值</button>
<br>
<span>{{message}}</span>
</div>
</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>
<div id="SecondChild">
<h1>{{message}}</h1>
</div>
</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組件之間的傳值--新入坑,請指教