vue 全局组件和局部组件

288 阅读1分钟

全局组件

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
     <div id="app">  
        <test-button></test-button>
    </div> 

    <template  id="vComponent">  // 当组件中template内容过多时可以像这样提出来写
         <span>我是用全局组件写出来的文字</span>
    </template>
    <script src="../vue.js"></script>
    <script>
        注册全局组件
         Vue.component('test-button',{
           template:'#vComponent'
         });
         var vm = new Vue({
             el: '#app',
             data: {

             }
         })
    </script>
</body>

</html>

局部组件

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id="app">  
        <part-component></part-component>
    </div>
    <script src="../vue.js"></script>
    <script>
        // 注册局部组件
        new Vue({
            el: '#app',
            components: {
                'part-component': {
                    template: '<span>对酒当歌,人生几何</span>'
                }
            }
        })
    </script>
</body>

</html>