1敬飒、父組件向子組件傳值
父組件paopao.vue
<template>
<div class="app-container">
<div id="paopao">
<Alert v-if="alert" v-bind:message="alert"></Alert>
</div>
</div>
</template>
<script>
import Alert from './Alert'
export default {
name: 'paopao',
data () {
return {
alert:'父組件向子組件傳遞的值'
}
},
components:{
Alert
}
}
</script>
2子組件Alert.vue
<template>
<div class="alert">
{{message}}
</div>
</template>
<script>
export default {
name: 'alert',
props:['message'],
data () {
return {
}
}
}
</script>
3邪铲、子組件向父組件傳值
子組件child.vue
titleChanged是父組件中綁定的函數(shù)名
<template>
<div class="child">
<input v-on:click="haha" type="button" value="子組件向父組件傳值">
</div>
</template>
<script>
export default{
data(){
return {
val:"子組件的value值"
}
},
methods:{
haha(){
this.$emit('titleChanged',this.val);
}
}
}
</script>
父組件father.vue
<template>
<div class="father">
<h1>{{faval}}</h1>
<child v-on:titleChanged="getValue"></child>
</div>
</template>
<script>
import child from './child.vue'
export default{
data(){
return {
faval:"Hello word!" }
},
components:{
child
},
methods:{
getValue(data){
this.faval = data
console.log(this.faval)
}
}
}
</script>
非父子組件傳遞值
非父子組件之間傳值,需要定義工具文件eventHub.js進(jìn)行傳值无拗,不然路由組件之間達(dá)不到傳值的效果
組件之間傳遞參數(shù)工具類eventHub.js
import Vue from 'vue'
export default new Vue()
組件A向組件B傳值
組件A.vue
<template>
<div class="classA">
<input type="button" value="A組件向B組件發(fā)送值" v-on:click="returnHome">
</div>
</template>
<script>
import Hub from './eventHub.js'
export default{
data(){
return {
msg:4
}
},
methods:{
returnHome(){
Hub.$emit('val',this.msg)
}
}
}
</script>
組件B.vue
<template>
<div class="classB">
<h3>{{name}}</h3>
</div>
</template>
<script>
import Hub from './eventHub.js'
export default{
data(){
return {
name:''
}
},
mounted:function(){
var that = this
Hub.$on('val',(data)=>{
that.name = data
})
}
}
</script>