Vue 开发实战基础篇 # 2:组件基础及组件注册

Posted 凯小默

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vue 开发实战基础篇 # 2:组件基础及组件注册相关的知识,希望对你有一定的参考价值。

说明

【Vue 开发实战】学习笔记。

组件

通常把可拆分的html,以及拆分后的逻辑,样式组合在一起称之为组件。

在 Vue 中,通过 Vue.component 定义(注册)一个组件:

<!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>
</head>
<body>
    <div id="app">
        message
        <ul>
            <todo-item v-for="item in list" :title="item.title" :del="item.del"></todo-item>
        </ul>

        <todo-list></todo-list>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        // 定义一个名为 todo-item 的组件;名字需要唯一
        Vue.component("todo-item", 
            props: 
                title: String,
                del: 
                    type: Boolean,
                    default: false
                
            ,
            template: `
                <li>
                    <span v-if="!del">title</span>
                    <span v-else style="text-decoration: line-through;">title</span>
                    <button v-show="del">删除</button>
                </li>
            `,
            // data 需要为函数返回一个对象,保证唯一性
            data: function() 
                return 
            ,
            methods: 
                
            ,
        );
        // 定义一个名为 todo-list 的组件
        Vue.component("todo-list", 
            template: `
                <ul>
                    <todo-item v-for="item in list" :title="item.title" :del="item.del"></todo-item>
                </ul>
            `,
            data: function() 
                return 
                    list: [
                        
                            title: "课程3",
                            del: true
                        ,
                            title: "课程4",
                            del: false
                        ,
                    ]
                
            ,
        );

        var vm = new Vue(
            el: "#app",
            data: 
                message: "kaimo 313",
                list: [
                    
                        title: "课程1",
                        del: true
                    ,
                        title: "课程2",
                        del: false
                    ,
                ]
            
        )
    </script>
</body>
</html>

以上是关于Vue 开发实战基础篇 # 2:组件基础及组件注册的主要内容,如果未能解决你的问题,请参考以下文章

Vue 开发实战基础篇 # 8:如何触发组件的更新

Vue 开发实战基础篇 # 3:Vue组件的核心概念:事件

Vue 开发实战基础篇 # 4:Vue组件的核心概念:插槽

Vue 开发实战基础篇 # 13:如何优雅地获取跨层级组件实例(拒绝递归)

Vue 开发实战基础篇 # 12:常用高级特性provide/inject

Vue 开发实战基础篇 # 10:生命周期的应用场景和函数式组件