DEV Community

huyixi
huyixi

Posted on

Vue的组件

非单文件组件

非单文件组件的使用

  • 创建组件
  const school = Vue.extend({
    //定义组件时不使用el,因为所有的组件都将使用vm管理
    template:`
        <div></div>
    `,
    data(){
        return{
              schoolname:'atguigu',
              address:'beijing'
        }
    },
    methods(){

    }
  })
Enter fullscreen mode Exit fullscreen mode
  • data写成函数 --- 避免组件复用时,数据存在引用关系

    • 注册组件
  • 局部注册组件

    //创建vm
    new Vue({
        //决定组件放在哪个容器下
        el:'#root'
        //注册组件
        components:{
            school
        }
    })
    
  • 全局注册组件

    vue.component('school',school)
    
    • 使用组件
  <school></school>
Enter fullscreen mode Exit fullscreen mode

注意点:

  • 组件的命名

    • 一个单词的组件命名
    • 首字母大写:School(推荐写法)
    • 全小写:school
    • 多个单词的组件命名
    • 首字母大写(kebab-case命名):MySchool(推荐写法)
    • 两个单词之间使用 - 连接(Camelcase命名):my-school
    • 可以在定义组件时使用name配置项指定组件在开发者工具中呈现的名字
  • 组件标签的写法

    • --- 自闭合写法

    不使用脚手架时,会导致后续组件无法渲染

  • 组件注册简写

  const school = Vue.extend({...})
  简写为:
  const school = {...}
Enter fullscreen mode Exit fullscreen mode

组件的嵌套

  • vm中只管理app一个组件
  new vue({
    el:'#root',
    components:{
        app
    }
  })
Enter fullscreen mode Exit fullscreen mode
  • app内包含其他组件
  const app = Vue.extend({
    components:{
        school,
        student
    }

  })
Enter fullscreen mode Exit fullscreen mode

VueComponent

  • school组件的本质是VueComponent的构造函数,由Vue.extend生成

  • 我们只需写组件标签,Vue解析时会帮助创建school组件的实例对象,即Vue帮助执行:new VueComponent(options)

  • 每次调用Vue.extend,返回的都是新的VueComponent

  • this指向:

    • 组件配置中: data函数,methods中的函数,watch中的函数,computed中的函数,他们的this都是VueComponent的实例对象
    • new Vue(options)配置中:
    • data函数,methods中的函数,watch中的函数,computed中的函数,他们的this都是Vue的实例对象
  • VueComponent以后自己简称为vc

Vue的实例对象以后简称为vm

组件的内置关系

vm拥有vc没有的一些功能比如el挂载点

单文件组件

App.vue

App.vue为入口文件,通过App.vue来管理所有组件

需要在App.vue中,引入,注册,使用组件

<template>
    <div>
        <School></School>
        <Student></Student>
</template>
<script>
    //引入组件
    import School from "./School";
    impotr Student from "./Student";
    //控制组件的交互
    export default {
        name:'App',
        //注册组件
        components: {
            School,
            Student
        }
    }
</script>
<style></style>
Enter fullscreen mode Exit fullscreen mode

main.js

通过main.js管理App.vue

需要引入,注册,使用 App.vue ,使用el指定容器

import App from "./App.vue"

new Vue({
    el: '#root',
})
Enter fullscreen mode Exit fullscreen mode

index.html

在index.html 中创建容器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div id="root"></div>
</body>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript" src="./main.js"></script>
</html>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)