javascript - 关于vue框架的局部组件注册问题?求解。。。
大家讲道理
大家讲道理 2017-04-11 13:15:22
0
3
414

vue框架有Vue.extend()方法,用来创建一个组件构造器,组件构造器创建之后需要注册(全局注册/局部注册)后才可以使用
例如:

    //我要局部注册组件,在官网上找到如下的例子
    var Child = Vue.extend({ /* ... */ })

    var Parent = Vue.extend({
      template: '...',
      components: {
        // <my-component> 只能用在父组件模板内
        'my-component': Child
      }
    })
    //但是我加上自己的理解写出来就是出问题了。
    <p id="example">
        <my-component> </my-component>
    </p>
    <script>
        var child=Vue.extend({
            template:"<p>子集的模版</p>"
        });
        var parent=Vue.extend({
            template:"<p>父集的模版</p>",
            components:{   //将子集的组件注册到父集
                'my-component': Child  //注册到父集之后就直接使用my-component这个模版吗?
            }
        })
        //这样的话我在页面会报错 如下:
        //vue.js:1023 [Vue warn]: Unknown custom element: <my-component> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
    </script>
按照我的理解,组件使用extend创建之后,都是需要注册的,那么我将一个子组件注册到父组件,那么子组件无法在外部调用,只有通过调用父组件才能使用子组件。那么是不是父组件也是需要在全局注册之后才能使用?望解答,顺便说下 上面的那段代码怎么写才是正确的?
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全員に返信(3)
大家讲道理

首先,上面的代码可以这样子跑起来。代码如下。或者去https://jsfiddle.net/qton08sd/ 看效果

    <p id="example">
        <parent> </parent>
    </p>
    <script>
        var Child = Vue.extend({
            template:"<p>子集的模版</p>"
        });
        var Parent = Vue.extend({
            template:"<p>父集的模版</p><my-component></my-component>",
            components:{   //将子集的组件注册到父集
                'my-component': Child  //注册到父集之后就直接使用my-component这个模版吗?
            }
        });
        new Vue({
            el: '#example',
          components: {
              'parent': Parent
          }
        });
    </script>

组件注册后,是需要使用的,Vue.js通过new Vue来创建实例。所以父组件的使用需要在new Vue中进行注册,然后在HTML中进行使用。

いいねを押す +0
迷茫

我也遇到这个报错,注意html里new Vue创建的实例不能包含在其他实例中,这样就好了

いいねを押す +0
Ty80
  1. 你的<my-component></my-component>注册在parent中

  2. parent未关联example

いいねを押す +0
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!