Vue.js 组件中调用函数的写法。

查看:1813
本文介绍了Vue.js 组件中调用函数的写法。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

    <div id="example">
    <component :is="component_name" @click="ccl()"></component>
    </div>
    var mycomponent = Vue.extend({
                    template: '<div>{{title}}hello component.</div>',
                    props: ['message'],
                    data: function () {
                        return {title: this.$root.message}
                    },
                    methods: {
                        ccl: function () {
                            alert('right');
                        }
                    }
                });

不是这么写的么?为什么我点击了以后没有反应呢?报错为VM9342:3 Uncaught TypeError: scope.ccl is not a function

解决方案

这个ccl不是组件的,而是他爹的方法。
你要在他爹的methods里面定义:

    Vue.component('child',{
        template: '<div>{{title}}hello component.</div>',
        props: ['message'],
    })
    var father=new Vue({
        el:"#example",
        data:{
            "component_name":'child'
        },
        methods:{
            ccl:function(){
                /**/
            }
        }
    })

理解好vue模板里面的作用域,就能够知道为什么了。。。

========2016年9月22日16:01:39 补充===========

怎么将父组件的数据传递给子组件

这个文档有说啊,用props:

   <component :is="xxx" :fatherMassage="msg"></component> 

然后父组件在data里面弄个msg的字段

    Vue.component('child',{
        template: '<div v-for="item in fatherMassage.data" >{{title}}hello component.</div>',
        props: ['fatherMassage'],
        ready:function(){
            console.log(this.fatherMassage.list)
        }
    })
    var father=new Vue({
        el:"#example",
        data:{
            "component_name":'child',
            "msg":{
                list:[xxx,xxx,xx,xx,x],
                data:[{
                    xxx:xxx,
                    xxx:xx
                },{
                    xxx:xx,
                    xxx:xx
                }]
            }
        },
        methods:{
            ccl:function(){
                /**/
            }
        }
    })

vue的作者尤大的文档写的很详细啦~~~~认真看下都会明白的

这篇关于Vue.js 组件中调用函数的写法。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆