Vue.js组件间传参问题

父组件向子组件传参

由于vue的组件都是独立的作用域,要想让父组件向子组件传参,必须在子组件中通过props选项来传递,子组件要在props中声明它想要获得的数据。

Vue.component('component-child', {
    props: ['vueMsg'],
    template: '<p>{{vueMsg}}</p>'
});

其声明想要获取父组件中的vue-msg参数信息,然后就可以模板代码中这样写。

<div id="component-1">
    <component-child vue-msg="hello"></component-child>
</div>

注意props中使用驼峰标识的字符串,在html中要转换为连字符的方式,因为html对大小写不敏感。如上述vueMsg要转换为vue-msg

这些还不够,如果想让父组件动态地向子组件传参,可以用v-bind来实现。每当父组件的数据变化时,该变化也会传导给子组件:

<div id="component-2">
    <input type="text" v-model="parentMsg"><br>
    <child v-bind:my-msg="parentMsg"></child>
</div>
new Vue({
    el: '#component-2',
    data: {
        parentMsg: 'Message from parent'
    },
    components: {
        child: {
            props: ['myMsg'],
            template: '<span>{{myMsg}}</span>'
        }
    }
});

v-bind还可以缩写成这样的形式

<child :my-msg="parentMsg"></child>

子组件向父组件传参

首先,要在父组件中声明子组件中触发哪个事件才会告知父组件子组件要传参,如子组件通过child-event事件来告知父组件要调用fatherEvent方法。

<div id="component-3">
    <p>{{msg}}</p>
    <child-component v-on:child-event="fatherEvent"></child-component>
</div>

那么在父组件中声明fatherEvent方法,用来处理子组件中传递过来的参数,如参数为msg

new Vue({
    el: '#component-3',
    data: {
        msg: 'I come from father'
    },
    methods: {
        fatherEvent: function(msg) {
            this.msg = msg;
        }
    }
});

此时子组件就可以向父组件中传递了

Vue.component('child-component',{
    template: '<button v-on:click="onClickMe">Click</button>',
    data: function() {
        return {
            msg: 'I am from child component'
        }
    },
    methods: {
        onClickMe: function() {
            //传递给父组件
            this.$emit('child-event', this.msg);
        }
    }
});

通过$emit来向父组件传参,第一个参数子组件要触发的事件,第二个为传递的参数。

注意:在$emit中第一个参数,不要使用驼峰标识,因为html对大小写不敏感。

然后,父组件接收了参数,将值赋给父组件中的msg,就可以在页面中显示出内容了。

如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注