0
点赞
收藏
分享

微信扫一扫

vue.js全局组件的三种方式

janedaring 2022-04-03 阅读 63

组件:button imageview listview等这些都是AS系统提供给我们
使用的组件;前端也有像类似于后端的组件概念。
组件的语法格式:
全局组件
Vue.component(‘组件名’,{代码的定义})
1.组件名称:
羊肉串法:my-comp-name ->
骆驼/pascal法: orderItem- 或
2.代码的定义
2.1 template:‘HTML代码’
2.2 template: 多行代码,反引号,是ECMAScript6之后提供给我们的符号;
2.3 template:外部定义的方式;
三种方式定义分别如下:
第一种方式,单引号(或双引号)

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>全局组件</title>
    <script src="../vue.js"></script>
</head>
<!-- 做下第一个组件的案例,后续前后端 开发会用到! -->

<body>
    <div id="app">
        <h3>{{msg}}</h3>
        <order-item></order-item>
    </div>
    <script>
        //1.需要针对order-item这个组件做一个定义,之前没有定义的;
        Vue.component('order-item',
            { template: '<ul><li>今天愚人节上课</li></ul>' }
        );
        let vm = new Vue({
            el: '#app',
            data: {
                msg: '全局组件的定义!'
            }
        });
    </script>
</body>

</html>

第二种方式反引号

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

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

<body>
    <div id="app">
        <order-item></order-item>
    </div>
    <div id="app1">
        <order-item></order-item>
    </div>
    <script>
        //1.定义组件;
        Vue.component('order-item', {
            template: `
                <div>
                    <h1>反引号的全局组件</h1>    
                    <p>京东特卖<p>
                    <ul><li>LV包包</li><li>GuCCI</li></ul>
                </div>
            `
        })
        //2.绑定
        new Vue({
            el: '#app'
        });
        new Vue({
            el: '#app1'
        });
    </script>
</body>

</html>

第三种方式外部ID

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

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

<body>
    <div id="app">
        <btn-counter></btn-counter>
    </div>
    <template id="btn-counter">
        <button @click="add">单击{{count}}次</button>
    </template>
    <script>
        //1.全局组件的定义;做个小作业做下测试;涵盖了:组件 data methods三种方式;
        Vue.component('btn-counter', {
            template: '#btn-counter',
            data: function () { return { count: 0 } },
            methods: { add: function () { this.count++ } }
        })
        //2.绑定;
        let vm1 = new Vue({ el: '#app' });
    </script>
</body>

</html>
举报

相关推荐

0 条评论