1.require.context()疾速注册

const path = require('path') const files = require.context('@/components/home', false, /.vue$/) const modules = {}files.keys().forEach(key => {const name = path.basename(key, '.vue')modules[name] = files(key).default || files(key) })components:modules

2.watch用法
immediate 立刻执行一次

watch: {  inpVal:{    handler: 'getList',      immediate: true  }}

deep 深度监听

watch:{  inpValObj:{    handler(newVal,oldVal){      console.log(newVal)      console.log(oldVal)    },    deep:true  }}
  1. 14种组件通信

1.props

// 数组:不倡议应用props:[]// 对象props:{ inpVal:{  type:Number, //传入值限定类型  // type 值可为String,Number,Boolean,Array,Object,Date,Function,Symbol  // type 还能够是一个自定义的构造函数,并且通过 instanceof 来进行查看确认  required: true, //是否必传  default:200,  //默认值,对象或数组默认值必须从一个工厂函数获取如 default:()=>[]  validator:(value) {    // 这个值必须匹配下列字符串中的一个    return ['success', 'warning', 'danger'].indexOf(value) !== -1  } }}
  1. $emit 子组件调用父组件
// 父组件<home @title="title">// 子组件this.$emit('title',[{title:'这是title'}])
  1. vuex
state:定义存贮数据的仓库 ,可通过this.$store.state 或mapState拜访getter:获取 store 值,可认为是 store 的计算属性,可通过this.$store.getter 或       mapGetters拜访mutation:同步扭转 store 值,为什么会设计成同步,因为mutation是间接扭转 store 值,         vue 对操作进行了记录,如果是异步无奈追踪扭转.可通过mapMutations调用action:异步调用函数执行mutation,进而扭转 store 值,可通过 this.$dispatch或mapActions       拜访modules:模块,如果状态过多,能够拆分成模块,最初在入口通过...解构引入
  1. attars 和 listeners

attars 获取未在子组件定义props的值

props: {  width: {    type: String,    default: ''  }},mounted() {  console.log(this.$attrs) //{title: "这是题目", height: "80", imgUrl: "imgUrl"}},

listeners 获取父组件的绑定事件

// 父组件<home @change="change"/>// 子组件mounted() {  console.log(this.$listeners) //即可拿到 change 事件}

inheritAttrs 为false 子组件无奈获取attrs

  1. provide和inject

父组件provide办法和属性 子组件通过inject应用

//父组件:provide: {   foo: '这是 foo'},mounted(){  this.foo='这是新的 foo'}// 子或者孙子组件inject: ['foo'], mounted() {  console.log(this.foo) //子组件打印的还是'这是 foo'}
  1. parent和children

this.$children 获取子组件
this.parent 获取父组件

  1. refs
    this.$refs.home

    1. $root

this.$root 获取根实例

  1. .sync 同步性能
`// 父组件<home :title.sync="title" />//编译时会被扩大为<home :title="title"  @update:title="val => title = val"/>// 子组件// 所以子组件能够通过$emit 触发 update 办法扭转mounted(){  this.$emit("update:title", '这是新的title')}`
  1. v-slot 插槽
// 父组件<todo-list>     <template v-slot:default>       任意内容       <p>我是匿名插槽 </p>    </template></todo-list> // 子组件<slot>我是默认值</slot>//v-slot:default写上感觉和具名写法比拟对立,容易了解,也能够不必写具名插槽<slot name="todo">我是默认值</slot>作用域插槽 子组件的数据在父组件中应用// 父组件<todo-list> <template v-slot:todo="slotProps" >   {{slotProps.user.firstName}} </template> </todo-list> //slotProps 能够随便命名//slotProps 接取的是子组件标签slot上属性数据的汇合所有v-bind:user="user"// 子组件<slot name="todo" :user="user" :test="test">    {{ user.lastName }} </slot> data() {    return {      user:{        lastName:"Zhang",        firstName:"yue"      },      test:[1,2,3,4]    }  },// {{ user.lastName }}是默认数据  v-slot:todo 当父页面没有(="slotProps")

11.EventBus 应用vue作为bus进行数据通信

// 在 main.jsVue.prototype.$eventBus=new Vue()// 传值组件this.$eventBus.$emit('eventTarget','这是eventTarget传过来的值')// 接管组件this.$eventBus.$on("eventTarget",v=>{  console.log('eventTarget',v);//这是eventTarget传过来的值})
  1. broadcast和dispatch 事件播送和派发

function broadcast(componentName, eventName, params) {  this.$children.forEach(child => {    var name = child.$options.componentName;    if (name === componentName) {      child.$emit.apply(child, [eventName].concat(params));    } else {      broadcast.apply(child, [componentName, eventName].concat(params));    }  });}export default {  methods: {    dispatch(componentName, eventName, params) {      var parent = this.$parent;      var name = parent.$options.componentName;      while (parent && (!name || name !== componentName)) {        parent = parent.$parent;        if (parent) {          name = parent.$options.componentName;        }      }      if (parent) {        parent.$emit.apply(parent, [eventName].concat(params));      }    },    broadcast(componentName, eventName, params) {      broadcast.call(this, componentName, eventName, params);    }  }}
  1. 路由参数
// 路由定义{  path: '/describe/:id',  name: 'Describe',  component: Describe}// 页面传参this.$router.push({  path: `/describe/${id}`,})// 页面获取this.$route.params.id 
// 路由定义{  path: '/describe',  name: 'Describe',  component: Describe}// 页面传参this.$router.push({  name: 'Describe',  params: {    id: id  }})// 页面获取this.$route.params.id// 路由定义{  path: '/describe',  name: 'Describe',  component: Describe}// 页面传参this.$router.push({  path: '/describe',    query: {      id: id  `})// 页面获取this.$route.query.id

14 Vue.observable
让一个对象可响应 能够模拟vuex

// 文件门路 - /store/store.jsimport Vue from 'vue'export const store = Vue.observable({ count: 0 })export const mutations = {  setCount (count) {    store.count = count  }}//应用<template>    <div>        <label for="bookNum">数 量</label>            <button @click="setCount(count+1)">+</button>            <span>{{count}}</span>            <button @click="setCount(count-1)">-</button>    </div></template><script>import { store, mutations } from '../store/store' // Vue2.6新增API Observableexport default {  name: 'Add',  computed: {    count () {      return store.count    }  },  methods: {    setCount: mutations.setCount  }}</script>

render函数

  1. 有些代码在template中反复太多
// 依据 props 生成标签// 高级<template>  <div>    <div v-if="level === 1"> <slot></slot> </div>    <p v-else-if="level === 2"> <slot></slot> </p>    <h1 v-else-if="level === 3"> <slot></slot> </h1>    <h2 v-else-if="level === 4"> <slot></slot> </h2>    <strong v-else-if="level === 5"> <slot></slot> </stong>    <textarea v-else-if="level === 6"> <slot></slot> </textarea>  </div></template>// 优化版,利用 render 函数减小了代码反复率<template>  <div>    <child :level="level">Hello world!</child>  </div></template><script type='text/javascript'>  import Vue from 'vue'  Vue.component('child', {    render(h) {      const tag = ['div', 'p', 'strong', 'h1', 'h2', 'textarea'][this.level-1]      return h(tag, this.$slots.default)    },    props: {      level: {  type: Number,  required: true  }     }  })     export default {    name: 'hehe',    data() { return { level: 3 } }  }</script>
异步组件

我的项目过大会导致加载迟缓
1.异步注册组件

// 工厂函数执行 resolve 回调Vue.component('async-webpack-example', function (resolve) {  // 这个非凡的 `require` 语法将会通知 webpack  // 主动将你的构建代码切割成多个包, 这些包  // 会通过 Ajax 申请加载  require(['./my-async-component'], resolve)})// 工厂函数返回 PromiseVue.component(  'async-webpack-example',  // 这个 `import` 函数会返回一个 `Promise` 对象。  () => import('./my-async-component'))// 工厂函数返回一个配置化组件对象const AsyncComponent = () => ({  // 须要加载的组件 (应该是一个 `Promise` 对象)  component: import('./MyComponent.vue'),  // 异步组件加载时应用的组件  loading: LoadingComponent,  // 加载失败时应用的组件  error: ErrorComponent,  // 展现加载时组件的延时工夫。默认值是 200 (毫秒)  delay: 200,  // 如果提供了超时工夫且组件加载也超时了,  // 则应用加载失败时应用的组件。默认值是:`Infinity`  timeout: 3000})

异步组件实质是渲染两次 第一次渲染加载占位
2.路由的按需加载

webpack< 2.4 时{  path:'/',  name:'home',  components:resolve=>require(['@/components/home'],resolve)}webpack> 2.4 时{  path:'/',  name:'home',  components:()=>import('@/components/home')}import()办法由es6提出,import()办法是动静加载,返回一个Promise对象,then办法的参数是加载到的模块。相似于Node.js的require办法,次要import()办法是异步加载的。
动静组件

切换一个tab用is
`<component v-bind:is="currentTabComponent"></component>
`
每次组件加载 应用

<keep-alive>  <component v-bind:is="currentTabComponent"></component></keep-alive>

没有动画 用内置的办法

<transition><keep-alive>  <component v-bind:is="currentTabComponent"></component></keep-alive></transition>

递归组件

// 递归组件: 组件在它的模板内能够递归的调用本人,只有给组件设置name组件就能够了。// 设置那么House在组件模板内就能够递归应用了,不过须要留神的是,// 必须给一个条件来限度数量,否则会抛出谬误: max stack size exceeded// 组件递归用来开发一些具体有未知层级关系的独立组件。比方:// 联级选择器和树形控件 <template>  <div v-for="(item,index) in treeArr">      子组件,以后层级值: {{index}} <br/>      <!-- 递归调用本身, 后盾判断是否不存在改值 -->      <tree :item="item.arr" v-if="item.flag"></tree>  </div></template><script>export default {  // 必须定义name,组件外部能力递归调用  name: 'tree',  data(){    return {}  },  // 接管内部传入的值  props: {     item: {      type:Array,      default: ()=>[]    }  }}</script>

递归组件必须设置name和完结的阈值