Vue2.0组件

161 阅读2分钟

基础结构

  1. .vue结尾,通过"vue-template-compiler": "^2.6.11"编译为.js文件
  2. 三个部分
    • template:模板结构
    • script: JS
    • style:CSS
<template>
  <div>
    <p>{{ name }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "li"
    }
  }
}
</script>

<style>
  p {
    background-color: pink;
  }
</style>

注意:1.组件中的data是一个函数,原因是组件时可以多次重复使用的,但是使用时可能绑定的数据是不一致的2.HTML结构中只能有一个根元素(Vue3可以有多个)

组件使用

  1. 父组件中引入子组件
<template>
    <div>
        ...
        <Child />
    </div>
</template>

<script>
improt xxx from 'yyy'

exprot default {
    ...
    componets: {
        xxx
    }
}
</script>

全局注册main.js

improt xxx from 'yyy'
Vue.component('zzz', xxx)

组件的样式冲突

vue 为 style 节点提供了 scoped 属性,使样式只对当前组件有效

修改当前组件中引入的子组件样式

/deep/+选择器,就能只修改引入组件在当前组件中的样式

props

组件的自定义属性,封装组件时,使用提高组件的复用性,例如有一个组件C,在A,B组件中需要被复用,但是A中需要它的初始值是6,B中希望其是9

image.png

props两种形式

  1. 数组:最简单的使用,只能接收值
  2. 对象
props: {
    init: {
        defalut: 7, // 默认值
        type: Number, // 数据类型
        required: true // 是否为必须
    }
}

props为只读

// 需要修改,可以传递给data
props: ["init"]

data() {
    return {
        count: this.props
    }
}

组件的生命周期(Life Cycle)

  1. 组件创建阶段

new Vue()/组件被使用-beforeCreate-created-beforeMount-mounted

  1. 组件运行阶段

beforeUpdate-updated

  1. 组件销毁阶段

beforeDestroy-destroyed image.png

组件之间的数据传递

父子关系

  1. 父组件向子组件(props)
  2. 子组件向父组件(自定义事件this.$emit)

image.png

兄弟关系

  1. Vue2Eventbus

image.png

ref引用

  1. ref
    • 引用DOM元素
    <input ref="ipt" type="text" />
    this.$refs.ipt // 获取到input
    
    • 引用组件实例
    <Count ref="countRef"/>
    this.$refs.countRef.add() // 引用Count实例的方法
    
    
  2. this.$nextTick(cb)

组件的 $nextTick(cb) 方法,会把 cb 回调推迟到下一个 DOM 更新周期之后执行。通俗的理解是:等组件的 DOM 更新完成之后,再执行 cb 回调函数。从而能保证 cb 回调函数可以操作到最新的 DOM 元素