Vue组件的编写

Vue组件的编写分为三个步骤,声名组件,挂载子组件,使用子组件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="success">
<!--使用组件-->
    <first></first>
    <second></second>
    <third></third>
</div>

</body>
<script src="vue.js"></script>
<script>
<!--子组件编写,声明组件-->
    let first = {
        data() {
            return {
                user_list: ['name', 'jack', 'age']
            }
        },
        template: '<h1>{{user_list}}</h1>',
    }
    let second = {
        data() {
            return {
                user_list: ['name', 'jack', 'age']
            }
        },

        template: '<h1 style="color: greenyellow">{{user_list}}</h1>'
    }
    
<!--全局组件编写-->
    Vue.component('third', {
        data() {
            return {
                data_dict: {name: 'jack', age: 18}
            }
        }, template: '<h1 style="color: brown">{{data_dict}}</h1>'
    })
    let vm = new Vue({
        el: '#success',
        data() {
            return {
                data: '123'
            }
        },

<!--在Vue中注册,挂载组件-->
        components: {  
            first,
            second
        }
    })
</script>
</html>

效果

以上的写法比较混乱,Vue对象中,最好不要零散的组件,所以就有了以下的这种方法,公司开发的过程中主要使用以下方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
      ---------------------------------------------
<div id="app">
    <App></App>
</div>
      ---------------------------------------------
</body>
<script src="vue.js"></script>
<script>
    let mm = {
        data() {
            return {
                user_list: ['name', 'jack', 'age']
            }
        },
        template: '<h1>{{user_list}}</h1>',
    }
    let ss = {
        data() {
            return {
                user_list: ['name', 'jack', 'age']
            }
        },

        template: '<h1 style="color: greenyellow">{{user_list}}</h1>'
    }
    Vue.component('cc', {
        data() {
            return {
                data_dict: {name: 'jack', age: 18}
            }
        }, template: '<h1 style="color: brown">{{data_dict}}</h1>'
    })
    ---------------------------------------------
        let App = {
        template:
            `
            <div class="app">
                <mm></mm>
                <ss></ss>
                <cc></cc>
            </div>
            `,
        components: {
            mm,
            ss,
        }
      ---------------------------------------------
    let vm = new Vue({
        el: '#app',
        components: {
           App,
        }
    }  
      ---------------------------------------------
</script>
</html>
posted @ 2022-03-31 23:55  recordlife  阅读(374)  评论(0编辑  收藏  举报