Skip to content

Vue 2 API 速查 ​

汇总 Vue 2.x 中常用的全局配置、全局 API、选项、实例属性与实例方法、模板修饰符、组件通信和工程化配置。

一、全局配置 ​

1. errorHandler ​

全局错误捕获函数,捕获渲染和观察期间未捕获的错误。

js
// main.js
Vue.config.errorHandler = function (err, vm, info) {
  // handle error
  // `info` 是 Vue 特定的错误信息,比如错误所在的生命周期钩子
  // 只在 2.2.0+ 可用
};

2. keyCodes ​

自定义按键修饰符的别名。

js
// main.js
Vue.config.keyCodes = {
  v: 86, // 前面是自定义名称,后面是 keyCode 值
  mediaPlayPause: 179, // camelCase 不可用
  "media-play-pause": 179, // 使用 kebab-case
  up: [38, 87], // 也可以接受一个数组
};
html
<input type="text" @keyup.media-play-pause="method" />

元素处于 focus 状态时才可能触发键盘事件。

二、全局 API ​

1. Vue.extend(options) ​

使用基础 Vue 构造器,创建一个子类。

html
<div id="mount-point"></div>
js
// 创建构造器
var Profile = Vue.extend({
  template: "<p>{{ firstName }} {{ lastName }} aka {{ alias }}</p>",
  data: function () {
    return {
      firstName: "Walter",
      lastName: "White",
      alias: "Heisenberg",
    };
  },
});

// 创建 Profile 实例,并挂载到一个元素上
new Profile().$mount("#mount-point");

渲染结果:

html
<p>Walter White aka Heisenberg</p>

2. Vue.directive(id, [definition]) ​

注册或获取全局指令。

指令注册 ​

js
Vue.directive("my-directive", {
  bind: function () {}, // beforeMount,指令绑定到元素后调用
  inserted: function () {}, // mounted,元素插入父节点后调用
  update: function () {},
  componentUpdated: function () {}, // updated,组件和子级被更新时调用
  unbind: function () {}, // destroyed,指令被移除时调用
});

钩子函数参数 ​

参数说明
el指令绑定的 DOM 元素
binding绑定信息对象,包含 name、value、arg、modifiers 等字段
vnodeVue 编译生成的虚拟节点

binding 中常用的字段:

  • name:指令名,不包括 v- 前缀。
  • value:指令的绑定值,例如 v-a="1 + 1" 的绑定值为 2。
  • arg:传给指令的参数,例如 v-a:bb 的参数为 bb。

动态指令参数 ​

指令的参数可以是动态的:

html
<div id="dynamicexample">
  <h3>Scroll down inside this section ↓</h3>
  <p v-pin:[direction]="200">200px to the left.</p>
</div>
js
Vue.directive("pin", {
  bind: function (el, binding, vnode) {
    el.style.position = "fixed";
    var s = binding.arg == "left" ? "left" : "top";
    el.style[s] = binding.value + "px";
  },
});

new Vue({
  el: "#dynamicexample",
  data: function () {
    return {
      direction: "left",
    };
  },
});

如果指令需要多个值,可以传入一个 JavaScript 对象字面量:

html
<div v-demo="{ color: 'white', text: 'hello' }"></div>
js
Vue.directive("demo", function (el, binding) {
  console.log(binding.value.color); // white
  console.log(binding.value.text); // hello
});

指令模块化 ​

  1. 新建 directive.js

    js
    const directive = function (Vue) {
      // 在此函数中,可注册多个全局指令
      Vue.directive("change-color", {});
    };
    
    export default directive;
  2. 在 main.js 中引入

    js
    // main.js
    import directive from "./directive";
    
    Vue.use(directive);
  3. 在组件中使用

    html
    <div v-change-color="color">{{ message }}</div>

3. Vue.filter(id, [definition]) ​

注册或获取全局过滤器,常用于一些常见的文本格式化。

html
<!-- 在双花括号中 -->
{{ message | capitalize }}

<!-- 在 v-bind 中 -->
<div :id="rawId | formatId"></div>

过滤器模块化 ​

js
const filters = function (Vue) {
  Vue.filter("capitalize", function (value) {
    // 处理逻辑
  });
};

export default filters;
js
// main.js
import filters from "./filter";

Vue.use(filters);

当全局过滤器和局部过滤器重名时,会使用局部过滤器。

过滤器串联 ​

html
{{ message | filterA | filterB }}

这里会将 message 的值传入 filterA,再把 filterA 的返回值传入 filterB。

过滤器接收参数 ​

html
{{ message | filterA('arg1', 'arg2') }}

filterA 被定义为接收三个参数的过滤器函数,其中 message 的值作为第一个参数,普通字符串 arg1、arg2 作为第二、第三个参数。

局部过滤器(选项式 API) ​

js
filters: {
  capitalize(message) {
    // 处理逻辑
  },
}

4. Vue.component(id, [definition]) ​

注册或获取全局组件。

js
// 注册组件,传入一个扩展过的构造器
Vue.component(
  "my-component",
  Vue.extend({
    /* ... */
  }),
);

// 等同于:注册组件,传入一个选项对象(自动调用 Vue.extend)
Vue.component("my-component", {
  /* ... */
});

// 获取注册的组件(始终返回构造器)
var MyComponent = Vue.component("my-component");

5. Vue.use(plugin) ​

安装 Vue.js 插件:

  • 如果插件是一个对象,必须提供 install 方法;install 方法调用时,会将 Vue 作为参数传入。
  • 该方法需要在调用 new Vue() 之前被调用。
  • 当 install 方法被同一个插件多次调用,插件只会被安装一次。
js
// 插件
import view from "./view.vue"; // 引入一个组件

let butt = {};

butt.install = function (Vue, options) {
  Vue.component("view.name", view);
};

export default butt;

使用:

js
// main.js
import wjButton from "../packages/button/index";

Vue.use(wjButton);
html
<!-- 在其他单文件组件中 -->
<wj-button></wj-button>

6. Vue.mixin(mixin) ​

混入:mixin 中的 data、methods、生命周期都会合并到当前组件中。

全局混入 ​

js
// mixin.js
export const authModuleMixin = {
  methods: {
    aaa() {},
  },
};
js
// main.js
import { authModuleMixin } from "./authModuleMixin";

Vue.mixin(authModuleMixin);

提示

  1. methods 中的方法合并时,如果命名冲突,组件中的方法会覆盖混入对象中的同名方法。
  2. 混入对象中的钩子函数在组件钩子函数之前调用。

局部混入(推荐) ​

js
// mixin.js
export const myMixin = {
  data() {
    return {
      number: "1",
    };
  },
  created() {
    console.log(this.number);
  },
};
vue
<!-- 引入混入 -->
<script>
import { myMixin } from "./mixin.js";

export default {
  mixins: [myMixin],
};
</script>

7. Vue.prototype ​

定义全局属性或方法。

在 template 中打印信息 ​

js
// main.js
Vue.prototype.$log = window.console.log;
html
<!-- 组件内部 -->
<div>{{ $log(info) }}</div>

挂载 echarts ​

js
// 引入 echarts
import echarts from "echarts";

Vue.prototype.$echarts = echarts;
js
// 使用
let myChart = this.$echarts.init(document.getElementById("myChart"));

三、选项 / 数据 ​

1. data ​

Vue 实例的数据对象,Vue 会递归地把 data 的属性转为 getter/setter,从而让数据具备响应式能力。

如果 data 是对象,所有实例将共享同一个数据对象;组件中应始终把 data 声明为函数。

js
data() {
  return { a: 1 }
}

2. props ​

props 可以是数组或对象,用于接收来自父组件的数据。

js
props: {
  // 检测类型
  height: Number,
  // 检测类型 + 其他验证
  age: {
    type: Number,
    default: 0,
    required: true,
    validator: function (value) {
      return value >= 0
    },
  },
}

3. computed ​

计算属性基于响应式依赖进行缓存,只有依赖项发生改变时才会重新求值。

js
computed: {
  reversedMessage() {
    return this.message.split('').reverse().join('')
  },
}

4. methods ​

methods 将被混入到 Vue 实例中,可以直接通过实例访问这些方法,或者在指令表达式中使用。方法中的 this 自动绑定为 Vue 实例。

js
methods: {
  plus() {
    this.a++
  },
}

注意:不应该使用箭头函数来定义 method(例如 plus: () => this.a++)。箭头函数绑定了父级作用域的上下文,this 不会按期望指向 Vue 实例,this.a 将是 undefined。

5. watch ​

默认惰性执行 ​

当值改变时才开始执行监听函数,第一次绑定时不执行。

js
watch: {
  inputName(newVal, oldVal) {
    this.fullName = newVal + '-'
    console.log(this.fullName)
    console.log(oldVal)
  },
}

立即执行 ​

如果希望第一次绑定值时就执行监听函数,需要用到 handler 方法和 immediate 属性。

js
watch: {
  inputName: {
    // 本来是直接写 inputName 方法,这里改为对象
    handler(newVal, oldVal) {
      this.fullName = newVal + '-'
      console.log(this.fullName)
      console.log('oldVal', oldVal)
      // 输入 1234
    },
    immediate: true,
  },
}

深度监听 ​

普通的 watch 方法无法监听到对象内部属性值的改变。

js
watch: {
  city: {
    handler(newVal, oldVal) {
      console.log(newVal)
      console.log('oldVal', oldVal)
    },
    deep: true,
  },
}

提示:如果整个对象被重新赋值,比如 this.obj = { a: '12' },则不需要深度监听。

监听对象中某个属性 ​

js
watch: {
  'city.name': {
    // 使用字符串的形式监听对象的属性
    handler(newVal, oldVal) {
      console.log(newVal)
      console.log('oldVal', oldVal)
      // 输入 好
    },
    deep: true,
  },
}

示例:监听 Vuex 的 state ​

js
computed: {
  getStore() {
    return this.$store.state
  },
},
watch: {
  getStore: {
    handler(newValue, preValue) {
      console.log(newValue)
    },
    deep: true,
    immediate: true,
  },
},

四、选项 / DOM、资源、组合与事件 ​

1. el ​

在实例挂载之后,可以通过 vm.$el 访问组件根元素。

js
mounted() {
  console.log(this.$el)
},

如果在实例化时存在这个选项,实例将自动调用 $mount 进入编译过程;否则需要显式调用 vm.$mount() 手动开启编译。

源码位置 src/core/instance/init.js:

js
Vue.prototype._init = function (options?: Object) {
  const vm: Component = this

  // 省略一系列其它初始化的代码

  if (vm.$options.el) {
    console.log('vm.$options.el:', vm.$options.el)
    vm.$mount(vm.$options.el)
  }
}

2. components ​

包含 Vue 实例可用组件的哈希表。

js
import LoginForm from "./components/loginForm";

export default {
  components: {
    LoginForm,
  },
};

3. provide / inject ​

provide 和 inject 的绑定不是可响应的:当外层 provide 的值改变时,inject 的值不会改变。

js
// 父组件
provide() {
  return {
    msg: this.title,
  }
},
js
// 子孙组件
inject: ['msg', 'fooMethod'],

4. vm.$emit(自定义事件) ​

html
<!-- 父组件 -->
<home @update:model="title" />
js
methods: {
  title(value) {
    console.log(value)
  },
},
js
// 子组件
this.$emit("update:model", [{ title: "这是 title" }]);

v-on 事件监听器在 DOM 模板中会被自动转换为全小写(HTML 是大小写不敏感的),所以 @myEvent 将会变成 @myevent,导致 myEvent 不可能被监听到。因此,始终使用 kebab-case 的事件名。

五、实例属性 ​

1. vm.$refs ​

访问通过 ref 注册的 DOM 元素或组件实例。

2. vm.$attrs ​

没有通过 props 接收的属性,都能在 this.$attrs 中访问到;可以通过 v-bind="$attrs" 把父组件传递的属性和方法全部传给自己的子组件。

html
<!-- 父组件 -->
<template>
  <HelloWorld :msg="msg"></HelloWorld>
</template>
html
<!-- 子组件 -->
<child v-bind="$attrs"></child>
js
// 孙子组件
props: {
  msg: {
    type: String,
  },
},

3. vm.$listeners ​

包含了父组件(不含 .native 修饰器的)v-on 事件监听器,可以用来让子组件调用父组件的方法。

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

六、实例方法 / 数据 ​

1. vm.$set(target, propertyName, value) ​

向响应式对象中添加一个属性,并确保这个新属性同样是响应式的。

2. vm.$delete(target, propertyName) ​

删除对象的属性;如果对象是响应式的,确保删除能触发视图更新。

七、实例方法 / 生命周期 ​

1. vm.$mount([elementOrSelector]) ​

如果 Vue 实例在实例化时没有收到 el 选项,则它处于未编译、未挂载状态,没有相关联的 DOM 元素,可以调用 vm.$mount() 手动挂载实例。

如果没有提供 elementOrSelector 参数,模板将被渲染为文档之外的元素,必须使用原生 DOM API 把它插入文档中。

js
var MyComponent = Vue.extend({
  template: "<div>Hello!</div>",
});

// 创建并挂载到 #app(会替换 #app)
new MyComponent().$mount("#app");

// 同上
new MyComponent({ el: "#app" });

// 或者,在文档之外渲染并且随后挂载
var component = new MyComponent().$mount();
document.getElementById("app").appendChild(component.$el);

2. vm.$nextTick([callback]) ​

在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,可以获取更新后的 DOM。

js
methods: {
  // ...
  example: function () {
    // 修改数据
    this.message = 'changed'
    // DOM 还没有更新
    this.$nextTick(function () {
      // DOM 现在更新了
      // `this` 绑定到当前实例
      this.doSomethingElse()
    })
  },
}

八、模板语法与修饰符 ​

1. .native 修饰符 ​

在一个组件的根元素上直接监听一个原生事件。

html
<div id="app">
  <my-component v-on:click.native="clickFun"></my-component>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  Vue.component("my-component", {
    template: `<a href='#'>click me</a>`,
  });

  new Vue({
    el: "#app",
    methods: {
      clickFun: function () {
        console.log("message: success");
      },
    },
  });
</script>

本来在组件上定义事件是不生效的,只有加了 .native 才生效。

2. Class 与 Style 绑定 ​

绑定类名 ​

对象语法:

html
<div class="static" :class="{ activeClass: isActive }"></div>
js
data: {
  isActive: true,
}

渲染结果:

html
<div class="static active"></div>

数组语法:

html
<div :class="[isActive ? 'activeClass' : 'errClass', 'comClass']"></div>

绑定内联样式 ​

html
<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
js
data: {
  activeColor: 'red',
  fontSize: 30,
}

3. 事件修饰符 ​

事件默认采用冒泡模式(在捕获阶段不执行,在冒泡阶段执行)。

修饰符作用
.stop阻止事件继续传播
.prevent阻止浏览器默认事件
.capture让事件在捕获阶段执行
.self只当 event.target 是当前元素自身时才触发处理函数
.once事件只触发一次,第一次点击有效,之后无效
.passive通知浏览器不阻止默认事件,跳过内核线程查询,提升滚动流畅度

基础示例:

html
<template>
  <div
    @click="clickOne"
    id="div1"
    style="background: blue; width: 100px; height: 100px"
  >
    <div
      @click="clickTwo"
      id="div2"
      style="background: red; width: 70px; height: 70px"
    >
      <div
        @click="clickThree"
        id="div3"
        style="background: yellow; width: 50px; height: 50px"
      ></div>
    </div>
  </div>
</template>

<script>
  export default {
    methods: {
      clickOne() {
        console.log("1");
      },
      clickTwo() {
        console.log("2");
      },
      clickThree() {
        console.log("3");
      },
    },
  };
</script>

点击最小的 div3 区域,打印 3, 2, 1,即冒泡事件。

.stop:阻止事件继续传播 ​

html
<div
  @click="clickOne"
  id="div1"
  style="background: blue; width: 100px; height: 100px"
>
  <div
    @click="clickTwo"
    id="div2"
    style="background: red; width: 70px; height: 70px"
  >
    <div
      @click.stop="clickThree"
      id="div3"
      style="background: yellow; width: 50px; height: 50px"
    ></div>
  </div>
</div>

点击最小的 div3 区域,打印 3。

html
<div
  @click="clickOne"
  id="div1"
  style="background: blue; width: 100px; height: 100px"
>
  <div
    @click.stop="clickTwo"
    id="div2"
    style="background: red; width: 70px; height: 70px"
  >
    <div
      @click="clickThree"
      id="div3"
      style="background: yellow; width: 50px; height: 50px"
    ></div>
  </div>
</div>

点击最小的 div3 区域,打印 3, 2。

可以看出 .stop 阻止了事件继续传播。

.prevent:阻止浏览器默认事件 ​

html
<a href="http://www.w3school.com.cn" @click.prevent="preventMethod">W3School</a>

点击 <a> 标签,本来是跳转到新页面,现在通过 .prevent 阻止了默认事件,点击不会跳转,而是执行 preventMethod 方法。

.capture:事件在捕获阶段执行 ​

html
<div
  @click.capture="clickOne"
  id="div1"
  style="background: blue; width: 100px; height: 100px"
>
  <div
    @click="clickTwo"
    id="div2"
    style="background: red; width: 70px; height: 70px"
  >
    <div
      @click="clickThree"
      id="div3"
      style="background: yellow; width: 50px; height: 50px"
    ></div>
  </div>
</div>

点击 div3 区域,打印 1, 3, 2。

.self:只当 event.target 是当前元素自身时触发 ​

事件不会在冒泡阶段被触发,只有点击元素本身才执行函数。

html
<div
  @click.self="clickOne"
  id="div1"
  style="background: blue; width: 100px; height: 100px"
>
  <div
    @click="clickTwo"
    id="div2"
    style="background: red; width: 70px; height: 70px"
  >
    <div
      @click="clickThree"
      id="div3"
      style="background: yellow; width: 50px; height: 50px"
    ></div>
  </div>
</div>

点击 div3 区域,打印 3, 2。

.once:事件只触发一次 ​

html
<div
  @click.once="clickOne"
  id="div1"
  style="background: blue; width: 100px; height: 100px"
>
  <div
    @click="clickTwo"
    id="div2"
    style="background: red; width: 70px; height: 70px"
  >
    <div
      @click="clickThree"
      id="div3"
      style="background: yellow; width: 50px; height: 50px"
    ></div>
  </div>
</div>

点击 div1 打印 1,再次点击不再执行。

.passive:告诉浏览器不会阻止默认事件 ​

每次事件产生,浏览器都会查询是否有 prevent 阻止该次事件的默认动作。加上 .passive 就是告诉浏览器不用查询了,我们没用 prevent 阻止默认动作。

这里一般用在滚动监听 @scroll、@touchmove:滚动监听过程中移动每个像素都会产生一次事件,每次都使用内核线程查询 prevent 会使滑动卡顿。通过 .passive 跳过内核线程查询,可以大大提升滑动的流畅度。

html
<div v-on:scroll.passive="onScroll">...</div>

这个 .passive 修饰符尤其能提升移动端的性能。

九、组件 ​

1. 组件双向绑定 ​

v-model 本质是语法糖 ​

html
<input :value="inputValue" @input="inputValue = $event.target.value" />
html
<!-- 等价于 -->
<input v-model="inputValue" />

v-model 相当于:通过 value 字段传值,通过 @input 接收子组件触发的事件。

组件上的 v-model ​

一个组件上的 v-model 默认会利用名为 value 的 prop 和名为 input 的事件。

父组件:

html
<custom-input :value="modelValue" @input="modelValue = $event" />

子组件:

html
<input :value="value" @input="$emit('input', $event.target.value)" />

父组件可以使用双向绑定简化:

html
<custom-input v-model="modelValue" />

更改属性或事件名称 ​

需要在子组件中添加 model 选项。

vue
<template>
  <input :value="title" @input="$emit('update:title', $event.target.value)" />
</template>

<script>
export default {
  model: {
    prop: "title",
    event: "update:title",
  },
  props: ["title"],
};
</script>

父组件改为:

html
<custom-input :title="modelValue" @update:title="modelValue = $event" />

使用 .sync 优化(2.3+) ​

父组件改为:

html
<custom-input :title.sync="modelValue" />

使用 .sync 后,不仅传递了 title,并且监听了 update:title 事件,并把传递的值直接赋值给 title 所对应的属性。

注意:只能绑定一个双向的值。

2. 组件通信 ​

父传子 ​

子组件通过 props 接收数据。

html
<!-- 父组件 -->
<pie-model :model="aaa"></pie-model>
js
// 子组件
props: {
  // 子组件访问父组件数据的唯一接口
  model: {
    type: Object, // type 值可为 String、Number、Boolean、Array、Object、Date、Function、Symbol
    required: true, // 是否必传
    default: function () {
      return {}
    },
    validator(value) {
      // 校验
      return ['success', 'warning', 'danger'].indexOf(value) !== -1
    },
  },
},

拓展:可通过 $attrs 获取父传子中未在 props 定义的值。

html
<!-- 父组件 -->
<home title="这是标题" width="80" height="80" imgUrl="imgUrl" />
js
// 子组件
mounted() {
  // { title: '这是标题', width: '80', height: '80', imgUrl: 'imgUrl' }
  console.log(this.$attrs)
},

子传父 ​

通过 $emit 传递数据给父组件。

html
<!-- 父组件 -->
<home @update:model="title" />
js
methods: {
  title(value) {
    console.log(value)
  },
},
js
// 子组件
this.$emit("update:model", [{ title: "这是 title" }]);

注:v-on 后面的事件名不能使用驼峰式写法,因为 HTML 不区分大小写。

父调用子 ​

父组件通过 $refs 访问子组件实例。

html
<!-- 父组件 -->
<home ref="home" />
js
mounted() {
  // 即可拿到子组件的实例,就可以直接操作 data 和 methods
  console.log(this.$refs.home)
},

非父子组件通信 ​

常用方式:事件总线、Vuex、状态提升。

事件总线依赖实例上的四个方法:

  • vm.$emit:触发事件
  • vm.$on:监听事件
  • vm.$off:注销监听器
  • vm.$once:只监听一次
js
// main.js
Vue.prototype.$eventBus = new Vue();
js
// 传值组件
this.$eventBus.$emit("eventTarget", "这是 eventTarget 传过来的值");
js
// 接收组件
this.$eventBus.$on("eventTarget", (v) => {
  console.log("eventTarget", v); // 这是 eventTarget 传过来的值
});

组件自动化注册 ​

场景:页面需要导入多个组件。原始写法:

js
import lineModel from "@/components/BaseEchartsModel/LineModel";
import cylinderModel from "@/components/BaseEchartsModel/CylinderModel";

export default {
  components: { lineModel, cylinderModel },
};

通过 require.context 批量注册:

vue
<script>
const path = require("path");
const files = require.context("@/components/BaseEchartsModel", false, /\.vue$/);
const modules = {};

files.keys().forEach((key) => {
  const name = path.basename(key, ".vue");
  modules[name] = files(key).default || files(key);
});

export default {
  name: "baseEcharts",
  components: modules,
};
</script>

拓展:

  • require.context(组件所在目录, 是否查询子目录, 匹配文件名的正则表达式)
  • path.basename(path[, ext]) 返回 path 的最后一部分,尾部的目录分隔符会被忽略,ext 可用正则匹配去掉文件类型。这里提取文件名作为组件的 key 值。

3. 插槽 ​

v-slot: 可以简写为 #。

匿名插槽 ​

html
<!-- 父组件 -->
<todo-list>
  <template #default>
    <p>我是匿名插槽</p>
  </template>
</todo-list>
html
<!-- 子组件 -->
<slot>我是插槽默认值</slot>

具名插槽 ​

通过 name 定义插槽位置。

html
<todo-list>
  <template #todo>
    <p>我是具名插槽</p>
  </template>
</todo-list>
html
<!-- 子组件 -->
<slot name="todo">我是默认值</slot>

作用域插槽 ​

父组件可以访问子组件的数据。

html
<!-- 父组件 -->
<Child>
  <template v-slot="{ user }">{{ user.age }}</template>
</Child>
vue
<!-- 子组件 -->
<template>
  <div>
    子组件
    <slot :user="user"></slot>
  </div>
</template>

<script>
export default {
  data() {
    return {
      user: {
        age: 2,
      },
    };
  },
};
</script>

4. 递归组件 ​

组件在它的模板内可以递归地调用自己,只要给组件设置 name 即可。需要注意的是,必须给一个条件来限制递归数量,否则会抛出错误 max stack size exceeded。

组件递归常用来开发具有未知层级关系的独立组件,比如级联选择器和树形控件。

vue
<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 和结束的阀值。

5. keep-alive ​

缓存组件,在路由切换时保存组件内的状态。

新增两个生命周期:activated 和 deactivated。

属性说明
include字符串或正则表达式。只有名称匹配的组件会被缓存
exclude字符串或正则表达式。名称匹配的组件不会被缓存
max数字。超过这个缓存数,在新实例被创建之前,已缓存组件中最久没有被访问的实例会被销毁掉

使用 include 时,需要组件上有 name 属性:

js
export default {
  name: "HelloWorld", // 在组件中定义组件的 name 值,不是在路由中定义的
  data() {
    return {};
  },
};
html
<transition name="fade" mode="out-in">
  <keep-alive :include="aliveList" :max="10">
    <router-view></router-view>
  </keep-alive>
</transition>
js
data() {
  return {
    aliveList: ['HelloWorld'],
  }
},

注意:<keep-alive> 不会在函数式组件中正常工作,因为它们没有缓存实例。

十、工程化配置 ​

vue.config.js ​

使 SCSS 样式添加到全局:

bash
cnpm i sass-resources-loader --save
js
var HtmlWebpackPlugin = require("html-webpack-plugin");

new HtmlWebpackPlugin({
  inject: "body",
});

module.exports = {
  productionSourceMap: process.env.NODE_ENV === "production" ? false : true,
  publicPath: process.env.NODE_ENV === "production" ? "./" : "/",
  assetsDir: "static",
  lintOnSave: false, // eslint 代码检测
  devServer: {
    open: true, // 加载完自动打开浏览器
    host: "127.0.0.1",
    port: 8083,
    // proxy: {
    //   '/api': {
    //     target: 'http://jsonplaceholder.typicode.com',
    //     changeOrigin: true,
    //     pathRewrite: {
    //       '/api': '',
    //     },
    //   },
    // },
  },
  // css 相关配置
  css: {
    // 是否分离 css(开发时注释掉,否则修改 CSS 样式无法触发热更新)
    // extract: true,
    sourceMap: false,
    // css 预设器配置项
    loaderOptions: {
      sass: {
        prependData: `@import "@/assets/scss/index.scss";`,
      },
      postcss: {
        plugins: [],
      },
    },
    // 是否启用 CSS Modules for all css / pre-processor files
    requireModuleExtension: true,
  },
  chainWebpack: (config) => {
    // 移除 prefetch 插件,取消预加载,启用懒加载
    config.plugins.delete("prefetch");
    config.plugins.delete("preload");
    config
      .plugin("webpack-bundle-analyzer")
      .use(require("webpack-bundle-analyzer").BundleAnalyzerPlugin);
    config.resolve.alias.set(key, value);
    // 别名,比如 .set('@@', resolve('src/components'))
  },
  configureWebpack: {
    // externals 中的 key 用于 import,value 表示在全局中访问到的对象,即 window.echarts
    // 防止 webpack 将 CDN 引入的文件打包进去
    externals: {
      echarts: "echarts",
      "element-ui": "ELEMENT",
      axios: "axios",
      vue: "Vue",
      vuex: "Vuex",
      "vue-router": "VueRouter",
    },
  },
};