Vue 非单文件组件

来自姬鸿昌的知识库
跳到导航 跳到搜索

https://www.bilibili.com/video/BV1Zy4y1K7SH?p=54

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/vue.js"></script>
</head>
<body>
    <!--
        Vue 中使用组件的三大步骤:
            一、定义组件(创建组件)
            二、注册组件
            三、使用组件(写组件标签)

        一、如何定义一个组件?
            使用 Vue.extend(options) 创建,其中 options 和 new Vue(options) 时传入的那个 options 几乎一样,但也有点区别:
            区别如下:
                1.el 不要写,为什么?————最终所有的组件都要经过一个 vm 的管理,由 vm 中的 el 决定服务哪个容器。
                2.data 必须写成函数,为什么?————避免组件被复用时,数据存在引用关系。
            备注:使用 template 可以配置组件结构。

        
        二、如何注册组件?
            1.局部注册:靠 new Vue 的时候传入 components 选项
            2.全局注册:靠 Vue.component('组件名', 组件)

        
        三、编写组件标签:
            <school></school>
    -->
    <!-- 准备好一个容器 -->
     <div id="root">
        <hello></hello>
        <h1>{{msg}}</h1>
        <hr>
        <!-- 第三步:编写组件标签 -->
        <school></school>
        <hr>
        <!-- 第三步:编写组件标签 -->
        <student></student>
     </div>

     <div id="root2">
        <hello></hello>
     </div>
</body>
<script>

    //第一步:创建 school 组件
    const school = Vue.extend({
        // el:'#root', //组件定义时,一定不要写 el 配置项,因为最终所有的组件都要被一个 vm 管理,由 vm 决定服务于哪个容器。
        template:`
            <div>
                <h2>学校名称:{{schoolName}}</h2>
                <h2>学校地址:{{address}}</h2>
            </div>
        `,
        data(){
            return {
                schoolName:'尚硅谷',
                address:'北京昌平'
            }
        }
    })

    //第一步:创建 student 组件
    const student = Vue.extend({
        template:`
            <div>
                <h2>学生姓名:{{studentName}}</h2>
                <h2>学生年龄:{{age}}</h2>
            </div>
        `,
        data(){
            return {
                studentName:'张三',
                age:18
            }
        }
    })

    //第一步:创建 hello 组件
    const hello = Vue.extend({
        template:`
            <div>
                <h2>你好!{{name}}</h2>
            </div>
        `,
        data(){
            return {
                name:'Tom'
            }
        }
    })
    
    //全局注册组件
    Vue.component('hello', hello)
    
    //创建 vm
    new Vue({
        el:'#root',
        data(){
            return {
                msg:'welcome'
            }
        },
        // data:{
        //     schoolName:'尚硅谷',
        //     address:'北京昌平',
        //     studentName:'张三',
        //     age:18
        // }
        //第二步:注册组件(局部注册)
        components:{
            school, student
        }
    })

    new Vue({
        el:'#root2',
    })
</script>
</html>