vue单页面父子传递

触发的自定义事件要放到注册的组件上

1通过点击:

<div id="app">
    <div v-text="money" @click="reduce"></div>
    <child :m="money" @zdyclick="add"></child>
</div>
<template id="tempchild">
    <div @click="changern">{{m}}</div>
</template>

需要三套名字:changern——子组件的事件方法名,zdyclick——父级html上的自定义事件名,桥接父子组件,在子组件方法里触发发布,在父级html里使用,add——父组件的方法名,改变值

let child = {
    template:"#tempchild",
    props:{
        m:{
            type:Number,
            default:0
        }
    },
    methods:{
        changern(){
            this.$emit('zdyclick',120)
        }
    }
}
let vm = new Vue({
    el:'#app',
    data:{
        money:400
    },
    components:{child},
    methods:{
        add(val){
            this.money+=val
        },
        reduce(){
            this.money-=50
        }
    }
})

2通过input输入:

<div id="app">
    {{money}}
    <child :m="money" @zdyclick="gai"></child>
</div>
<template id="tempchild">
    <input type="text" :value="m" @input="changer"></input>
</template>
let child = {
    template:"#tempchild",
    props:{
        m:{
            type:Number,
            default:0
        }
    },
    methods:{
        changer(e){
            this.$emit('zdyclick',Number(e.target.value))
        }
    }
}
let vm = new Vue({
    el:"#app",
    data:{money:400},
    components:{child},
    methods:{
        gai(val){
            this.money = val
        }
    }
})
原文地址:https://www.cnblogs.com/liufeiran/p/11608018.html