子往父组件传值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <App></App>
</div>
<script src="vue.js"></script>
<script>
    //声明一个全局组件  Vbtn组件
    Vue.component("Vbtn",{
        data(){
            //return的返回值是传给父组件func_clickHandler()的???
            return{}//props:["id"] 声明完就相当于在return里绑定了
        },
        template:`<button @click="clickHandler">
            {{id}}
            </button>`,
        // 传过来的值id
        props:["id"],//声明之后可以在任何地方用,比如在模板中通过{{id}}可以获取,在method里通过this.id获取
        methods:{
            clickHandler(){ //这个方法出发父组件里的内容
                console.log(this);// 谁调用的这个函数,this就是谁,这里是Vbtn. 每个组价中的this指当前组件对象 *****
                this.id++
                //this.$emit("触发父组件中声明的事件","传值")*****
                //第二步:在子组件中通过$emit 触发父组件里绑定的自定义事件@clickHandler
                this.$emit("clickHandler",this.id);
            }
        }
    })

    let Vheader = {//对象
        data(){
            return {}
        },
        props:["msg","post"],

        // 第一步:先在父组件里自定义一个触发事件@clickHandler
        template:`
        <div>
            <h2>我是header组件</h2>
            <h2>生子是在子组件中</h2>
            <h2 style="color:red">挂子和用子是在父组件中</h2>
            <h3>{{msg}}</h3>
            <h3>{{post.title}}</h3>

            <Vbtn v-bind:id="post.id" @clickHandler="func_clickHandler"></Vbtn>
        </div>
        `,
        methods:{
            func_clickHandler(val){
                alert(val)
                this.$emit("fatherheader",val)
            }
        }
    }


    let App = { //跟的是一个对象  这个对象里 就是除了下面的Vue中,el以外的所有属性
        data() {
            // 父-->子传值 通过props 属性
            // 传入一个对象的多个属性post
            return {
                text: "我是Vheader的父组件,想把数据传过去",
                post:{
                    id:1,
                    title:"My journey with Vue"
                }
            }
        },

        template: `
        <div id="a">
            我是父组件的{{post.id}}
            <Vheader v-bind:msg="text" v-bind:post="post" @fatherheader="father_header"></Vheader>
        </div>
        `,
        //给子组件定义方法  比如说a标签的超链接
        methods:{
            father_header(val){
                this.post.id=val  //修改完数据对应的 我是父组件的{{post.id}}里的数据跟着修改
            }
        },
        components:{
            // 第二步:挂子2
            Vheader
        },
    }

    new Vue({
        el: "#app",  //绑定根元素  是上面的id="app"
        data() {
            return {msg: "alex"}
        },

        components: {
            // 第二步:   挂子 父组件Vue里不仅是可以挂载一个App,还可以挂载其他组件
            App   //如果key和value一样,可以只写App 替代App:App

        }
    })
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/kenD/p/10217009.html