Vue组件化

Vue组件化

一、基础概念

1、概念:组件是html、css、js等的一个聚合体

2、为什么要使用组件?

  • 组件化
  • 将一个具备完整功能的项目的一部分进行多处使用
  • 加快项目的进度
  • 可以进行项目的复用
  • 要想实现组件化,我们使用的这一部分必须是完整的,这个完整的整体称之为组件

3、vue将html、css、js、img等聚合体放在一起组成的文件称之为单文件组件,后缀名为vue(xxx.vue)

二、组件的创建

  • 引入vue.js文件之后,会向全局暴露一个Vue构造器函数
  • Vue.extend()是 vue 用来扩展 vue 功能(组件)的
  • Vue.extend()实例化与new Vue()是一样的,几乎没有区别,所以借鉴react,vue决定组件要以标签的形式呈现
  • 为了符合html/html5的规则,所有组件的标签化使用必须先注册(即创建)
  • 说明白点注册就是将标签化的组件解析为html能识别的标签,因为自己创建的标签需要符合html规则,让html正确解析该组件标签
  • 组件必须先注册再使用,使用是在实例范围内使用
  • 组件名称可以小写加-命名 如:header-title
  • 大驼峰 如:GabrielLi 使用的时候写gabriel-li (注册的时候写的是大写,使用的时候写小写加-,因为浏览器会自动将大写解析成小写)
  • 一个单词大写,注意不要和原生的h5标签重名,比如 header footer

1、全局注册

<div id="app">
    <Father>Father>   
div>
<div id="root">
    <Father>Father>   
div>

//组件的创建:Vue.component( 组件的名称,组件的配置项 )  
var Hello = Vue.extend({
    template:'
这是father组件
'
}) Vue.component('Father',Hello) // 组件Father不能在实例范围外使用 new Vue({ el:'#app' }) new Vue({ el:'#root' })

2、局部注册

局部注册在组件中用一个components的配置项来表示,只能在注册的范围内使用,其他地方不能使用

<div id="app">
    <zhang-san>zhang-san>
div>
    
var Hello = Vue.extend({
    template:'
这里是组件
'
}) new Vue({ el:'#app', components:{ 'zhang-san':Hello //key:value key是组件名称 value是组件配置项 } })

3、简写

<div id="app">
    <gabriel-li>gabriel-li>   
    <Father>Father>   
div>

Vue.component('Father',{
    template:'
全局注册
'
}) new Vue({ el:'#app', components:{ 'GabrielLi':{ template:'
局部注册
'
} } })

三、组件的嵌套

  • 父组件里面放子组件,类似dom结构的父子级结构
  • 将子组件以标签的形式放在父组件的模板中使用,千万不要放在父组件的内容中
<div id="app">
    <Father>Father>
div>
Vue.component('Father',{
    template:'
Father
'
}) Vue.component('Son',{ template:'
son
'
}) new Vue({ el:'#app' })

局部的写法

new Vue({
    el: '#app',
    components: {
      'Father': {
        template: '
father组件
'
, components: { 'Son': { template: '
son组件
'
// son组件嵌套在father组件中 } } } } })

四、组件的特殊使用规则

1、使用规则之is规则

  • 如果直属父子级直接组件以标签化形式使用,会有bug
<div id="app">
    <table>

      tr>   
    table>
div>
 Vue.component('Hello',{
    template: '  4   2  3 '
  })
  new Vue({
    el: '#app'
  })

2、使用规则之template

1、实例范围内使用

  • template中的内容被当做一个整体了,并且标签是不会解析到html结构中的
<div id="app">
    <template>   
      <div>
        <ul>
          <li>1li>
          <li>2li>
          <li>3li>
        ul>
      div>
    template>
div>
Vue.component('Hello',{
    template: ''
  })
  new Vue({
    el: '#app'
  })

2、实例范围外使用

  • 实例范围外template标签中的代码是不会被直接解析的
<div id="app">
<template>  
    <div>
      <ul>
        <li>1li>
        <li>2li>
      ul>
    div>
  template>
div>
Vue.component('Hello',{
    template: ''
  })
  new Vue({
    el: '#app'
  })

需要正确使用template,可以采用实例范围外方法,但是需要修改部分代码

<div id="#app">
  <Hello>Hello>  
  <template id="hello">   
    <div>
      	<ul>
        	<li>1li>
        	<li>2li>
     	 ul>
    div>
  template>
div>
Vue.component('Hello',{
    template: '#Hello'
  })
  new Vue({
    el: '#app'
  })

你可能感兴趣的:(Vue组件化)