zoukankan      html  css  js  c++  java
  • vue 组件 子向父亲通信用自定义方法用事件监听

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Title of page</title>
    </head>
    <body>


    <div id="example">
    <input v-model="parentsg">
    <br>
    <child v-bind:parentsg="parentsg"></child>
    <!-- 直接绑定根数据text ,但是必须指明根数据的路径shou.text-->
    <todo-item v-bind:todo="todo"></todo-item>
    </div>
    <div id="counter-event-example">
    <p>{{childtofather}}</p>
    <p>{{ total }}</p>
    <button-counter v-on:increment="incrementTotal"></button-counter>
    <button-counter v-on:increment="incrementTotal"></button-counter>
    </div>

    </body>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script>
    <script >
    // 注册
    Vue.component('child', {
    props: ['parentsg'],
    template: '<span>{{ parentsg}}</span>'
    })
    Vue.component('todo-item', {
    props: ['todo'],
    template: '<p>{{todo.isComplete}}</p>'
    })

    // 创建根实例
    new Vue({
    el: '#example',
    data:{

    parentsg:'',
    todo: {
    text: 'Learn Vue',
    isComplete: false
    },
    shou: {
    text: 'shi wo ma',
    isComplete: false
    }

    }

    })

    Vue.component('button-counter', {
    template: '<button v-on:click="incrementCounter">{{ counter }}</button>',
    data: function () {
    return {
    counter: 0
    }
    },

    // 绑定了事件click————>increment

    // 然后 this.counter += 1; this.$emit('increment1',this.counter);

    // 这边就是触发事件 increment1,参考文献里面有点乱,这边是不是清晰多了

    // 然后 <button-counter v-on:increment1="incrementTotal"></button-counter>

    // v-on相当于监听吧,就触发 incrementTotal

    // 传给父组件的参数 输出// this.counter

    // 有没有很清晰,若有理解不对的地方,请指正
    methods: {
    incrementCounter: function () {
    this.counter += 1
    this.$emit('increment',this.counter)
    }
    },
    })

    new Vue({
    el: '#counter-event-example',
    data: {
    total: 0,
    childtofather:''
    },
    methods: {
    incrementTotal: function (e) {

    this.total += 1;
    //输出 this.counter
    console.log(e)
    //
    this.childtofather=e +"子传父传来的数据"
    }
    }
    })
    </script>
    </html>

  • 相关阅读:
    [Java学习] Java包装类、拆箱和装箱详解
    [Java学习] Java多态和动态绑定
    [Java学习] Java继承的概念与实现
    [Java学习] Java super关键字
    [Java代码] Java是自学好还是参加培训班好?
    [Java学习] Java字符串(String)
    [Java学习] Java方法重载
    [.NET源码] EF的增删改查
    C#面向服务WebService从入门到精通
    CoordinatorLayout-带图片伸缩工具栏
  • 原文地址:https://www.cnblogs.com/dianzan/p/8504410.html
Copyright © 2011-2022 走看看