//...">
美文网首页
vue组件之间的通讯

vue组件之间的通讯

作者: a180754bf396 | 来源:发表于2017-09-21 08:23 被阅读0次

    使用props传递数据,组件内部

    <div id="app1">
    <child my-message="组件内部数据传递"></child>
    </div>
    //js
    <script>
    Vue.component('child', {
    props: ['myMessage'],
    template: '<mark>{{ myMessage }}<mark/>'
    });
    new Vue({
    el: '#app1'
    })
    </script>

    父子之间传送数据

    <div id="app2">
    <input v-model="parentMsg">


    <child :parent-msg="parentMsg"></child>
    </div>
    <script>
    Vue.component('child', {
    props: ['parentMsg'],
    template: '<mark>{{ parentMsg }}<mark/>'
    });
    new Vue({
    el: '#app2',
    data: {
    parentMsg: 'msg from parent!'
    }
    })
    </script>

    如果数据是引用对象则可以互传

    props: ['initialCounter'],
    data: function () {
    return { counter: this.initialCounter }
    }
    //定义一个局部computed属性,此属性从 prop 的值计算得出
    props: ['size'],
    computed: {
    normalizedSize: function () {
    return this.size.trim().toLowerCase()
    }
    }

    子子传数据

    $emit $on

    <div id="app3">
    <p>Look at the parent's data: <mark>{{t}}</mark> & the child's data: <mark>{{childWords}}</mark></p>
    <child v-on:add="pChange"></child>
    <child v-on:add="pChange"></child>
    <child v-on:click.native="native"></child>
    </div>
    <script>
    Vue.component('child', {
    template: <button @click="add">{{ c }}</button>,
    data: function () {
    return {
    c: 0,
    msg: 'I am from child's data'
    }
    },
    methods: {
    add: function () {
    this.c += 1;
    this.$emit('add',this.msg);
    }
    },
    });
    new Vue({
    el: '#app3',
    data: {
    t: 0,
    childWords: ''
    },
    methods: {
    pChange: function (msg) {
    this.t += 1;
    this.childWords=msg;
    },
    native:function () {
    alert('I am a native event ,which comes from the root element!');
    }
    }
    })
    </script>

    <div id="app4">
    <display></display>
    <increment></increment>
    </div>
    <script>
    var bus = new Vue();
    Vue.component('increment', {
    template: <button @click="add">+</button>,
    data: function () {
    return {count: 0}
    },
    methods: {
    add: function () {
    bus.$emit('inc', this.count+=1)
    }
    }
    });
    Vue.component('display', {
    template: <span>Clicked: <mark>{{c}}</mark> times</span>,
    data: function () {
    return {c: 0}
    },
    created: function () {
    var self=this;
    // bus.$on('inc', function (num) {
    // self.c = num
    // });
    bus.$on('inc', (num) =>
    this.c = num
    );
    }
    });
    vm = new Vue({
    el: "#app4",
    })
    </script>

    相关文章

      网友评论

          本文标题:vue组件之间的通讯

          本文链接:https://www.haomeiwen.com/subject/ceensxtx.html