美文网首页
vue笔记-13(组件基础)

vue笔记-13(组件基础)

作者: 7ColorLotus | 来源:发表于2020-09-23 15:02 被阅读0次

组件--基础

  • 什么是组件:组件的出现就是为了拆分Vue实例的代码量的,能够让我们以不同的组件,来划分不同的功能模块,将来我们需要什么样的功能,就可以取调用对应的组件即可
  • 组件化和模块化的不同:
    1. 模块化是从代码逻辑的角度进行划分的,方便代码分层开发,保证每个功能模块的智能单一
    2. 组件化是从UI界面角度进行划分的,方便UI组件的重用
  • 创建组件的方式
    1. 创建组件方式一:使用Vue.extend来创建全局的Vue组件

      //创建组件对象
      var com1 = Vue.extend({
          template: '<h3>这是使用Vue.extend创建的组件</h3>' //通过template属性,指定了组件要展示的HTML结构
      })
      
      //使用Vue.component('组件名称', 创建出来的组件模板对象)来使用组件
      Vue.component('myCom1', com1)
      
      //html中引用展示组件(如果组件名称使用驼峰则替换成中划线,否则直接使用组件名称)
      <my-com1></my-com1>
      
      
      //该方式可以简写为下面的方式
      Vue.component('mycom', Vue.extend({
          template: '<h3>这是使用Vue.extend创建的组件</h3>' //通过template属性,指定了组件要展示的HTML结构
      }))
      
      
    2. 创建组件方式二:直接使用component创建组件

        Vue.component('mycom2',{
            template: '<h3>这是直接使用Vue.component 创建的组件</h3>'
        })
      
    3. 无论使用哪种方式创建出来的组件,组件的模板内容必须有且只有一个根元素

    4. 创建组件方式三:通过<template>元素创建模板

      Vue.component('mycom2',{
          template: '#tmpl'
      })
      
      // 在被控制的#app外面,使用template元素,定义组件的HTML模板结构
      <template id="templ">
          <div> // 只有一个根元素
              <h1>这是通过template元素,在外部定义的组件结构,这个方式,有代码的智能提示和高亮</h1>
          </div>
      </template>
      
  • 代码demo
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>创建组件</title>
    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>

</head>
<body>
    <div id="app">
        <!-- 必须包含在vm实例指定的el中 -->
        <my-com1></my-com1> 

        <mycom2></mycom2>

        <mycom3></mycom3>
        
    </div>

    <template id="tmpl1">
        <div>
            <h3>这是template元素,在外部定义的组件结构</h3>
        </div>
    </template>


    <script>

        //方式一
        // var com1 = Vue.extend({
        //     template: '<h3>这是使用Vue.extend创建的组件</h3>'
        // })
        // Vue.component('myCom1', com1)
        
        //方式一的简写
        Vue.component('myCom1', Vue.extend({
            template: '<h3>这是使用Vue.extend创建的组件</h3>'
        }))

        //方式二 
        Vue.component('mycom2', {
            template: '<h3>这是使用方式二创建的组件</h3>'
        })
        
        //方式三
        Vue.component('mycom3',{
            template: '#tmpl1'
        })


        var vm = new Vue({
            el :"#app"
        })

    </script>
</body>
</html>

相关文章

网友评论

      本文标题:vue笔记-13(组件基础)

      本文链接:https://www.haomeiwen.com/subject/kdhoyktx.html