Vue.js 2.6尝鲜

在这篇文章中,将会介绍新版本的新特性, 比如slots的新语法,Vue.observable()等等

1. Scoped slots(作用域插槽)的新语法

这是一个比较重大的改变,包含的有:

  • v-slot新指令,结合了slotslot-scope的功能
  • scoped slots的简写

之前Vue@2.5.22中是这样使用scoped-slots的:

<template>
   <TestComponent>
     <! - 默认 scoped slot ->
     <div slot-scope="{message}">
       {{`Default slot with message: ${message}`}}
     </ div>
     <! - 具名 scoped slot ->
     <div slot="text" slot-scope="{text}">
       {{`Named slot with text: ${text}`}}
     </ div>
   </ TestComponent>
</ template>

现在是这样的:

<template>
   <TestComponent>
     <! - 默认 scoped slot ->
     <template v-slot="{message}">
       <div>
         {{`Default slot with message: ${message}`}}
       </ div>
     </ template>
     <! - 具名 scoped slot ->
     <template v-slot:text="{text}">
       <div>
         {{`Named slot with text: ${text}`}}
       </ div>
     </ template>
   </ TestComponent>
</ template>

默认插槽:

<template>
   <! - v-slot is used directly on the parent ->
   <TestComponent v-slot="{message}">
     <div>
       {{`Default slot with message: ${message}`}}
     </ div>
   </ TestComponent>
</ template>

具名插槽:

<template>
   <TestComponent>
     <! - # 简写: ->
     <template #text="{text}">
       <div>
         {{`Named slot with text: ${text}`}}
       </ div>
     </ template>
   </ TestComponent>
</ template>

新版中,可以不使用任何作用域插槽变量,但是仍然可以通过父组件的$scopedSlots去引用到

2. 动态参数指令

如果我们想在v-bind or v-on中使用动态变量,在Vue@2.5.22中:

<div v-bind="{ [key]: value }"></div>
<div v-on="{ [event]: handler }"></div>

但是这个例子有几个缺点:

不是所有人都知道在v-bind / v-on中可以使用动态变量名

vue-template-compier 生成了低效的代码

v-slot没有类似的使用对象的语法

为了解决这些问题,Vue@2.6.0引入了一个新语法:

<div v-bind:[key]="value"></div>
<div v-on:[event]="handler"></div>

举个例子:

<template>
   <div>
     <! - v-bind 动态key ->
     <div v-bind:[key]="value"> </ div>

     <! - 简写 ->
     <div :[key]="value"> </ div>

     <! - v-on 动态事件,event变量 ->
     <div v-on:[event]="handler"> </ div>

     <! - 简写 ->
     <div @[event]="handler"> </ div>

     <! - v-slot 动态名字 ->
     <TestComponent>
       <template v-slot:[name]>
         Hello
       </ template>
     </ TestComponent>

     <! - 简写 ->
     <TestComponent>
       <template #[name]>
         Cool slot
       </ template>
     </ TestComponent>
   </ div>
</ template>

3. 使用Vue.observable()创建一个响应对象

之前,创建一个响应对象,必须在一个Vue实例中配置。现在我们可以在Vue实例外部,通过使用Vue.observable(data)创建,如下:

import vue from vue;
const state = Vue.observable ({
   counter: 0,
});
export default {
   render () {
     return (
       <div>
         {state.counter}
           <button v-on:click={() => {state.counter ++; }}>
           Increment counter
         </ button>
       </ div>
     );
   },
};

4. server端获取数据

在新的升级版本中,vue-server-renderer改变了SSR的数据加载策略。

之前,我们推荐使用asyncData ()router.getMatchedComponents ()方法中获取的组件中,获取数据。

新版本中有一个特别的组件方法:serverPrefetch() 。vue-server-renderer会在每个组件中调用它,它会返回一个promise。

<template>
   <div v-if="item">
     {{item.name}}
   </ div>
</ template>
<script>
export default {
   // Call on the server
   async serverPrefetch () {
     await this.fetchItem();
   },
   computed: {
     item () {
       return this.$store.state.item;
     },
   },
   // Call on client
   mounted () {
     if (!this.item) {
       this.fetchItem();
     }
   },
   methods: {
     async fetchItem () {
       await this.$store.dispatch(&#39;fetchItem&#39;);
     },
   },
};
</ script>

serverPrefetch()执行之后,我们需要知道应用在什么时候渲染完成,在server render 上下文中,我们可以使用rendered()钩子方法。

/ * Simplified entry-server.js * /
import {createApp} from &#39;./app&#39;;
export default context => new Promise ((resolve, reject) => {
   const {app, router, store} = createApp();
   const {url} = context;
   router.push(url);
   router.onReady(() => {
     context.rendered = () => {
       context.state = store.state;
     };
     resolve (app);
   }, reject);
});

5. 改进的错误输出

render方法中编译html,vue-template-compiler可能会产生错误。在之前,Vue会产生一个没有位置的错误描述。新版本中会展示这个错误出现在哪里,比如:

<template>
  <div>
    <template key="test-key">
      {{ message }}
    </template>
  </div>
</template>

vue-template-compiler@2.5.22中:

Error compiling template:
<div>
    <template key="test-key">
      {{ message }}
    </template>
  </div>
- <template> cannot be keyed. Place the key on real elements instead.

vue-template-compiler@2.6.0中:

Errors compiling template:
<template> cannot be keyed. Place the key on real elements instead.
1  |
2  |  <div>
3  |    <template key="test-key">
   |              ^^^^^^^^^^^^^^
4  |      {{ message }}
5  |    </template>

6. 捕捉异步错误

现在Vue可以在生命周期方法钩子和事件方法中捕捉到异步错误异常。比如:

/ * TestComponent.vue * /
<template>
   <div @click="doSomething()">
     Some message
   </ div>
</ template>
<script>
export default {
   methods: {
     async doSomething () {
       await this.$nextTick ();
       throw new Error (&#39;Another Error&#39;);
     },
   },
   async mounted () {
     await this.$nextTick ();
     throw new Error (&#39;Some Error&#39;);
   },
};
</ script>

mount后错误:

[Vue warn]: Error in mounted hook (Promise/async): "Error: Some Error"

点击事件后错误:

[Vue warn]: Error in v-on handler (Promise/async): "Error: Another Error"

7. ESM 浏览器中的新版构建

新版本中,增加了一个vue.esm.browser.js。它是为了支持ES6 Modules的浏览器设计的。

特性:

  • 在render函数中,包含HTML编译器
  • 使用ES6模块语法
  • 包含非副本代码(non-transcript)

举例:

<html lang="en">
   <head>
     <title> Document </ title>
   </ head>
   <body>
     <div id="app">
       {{message}}
     </ div>
     <script type="module">
       import Vue from &#39;path/to/vue.esm.browser.js&#39;;
       new Vue {{
         el: &#39;#app&#39;,
         data () {
           return {
             message: &#39;Hello World!&#39;,
           };
         },
       });
     </ script>
   </ body>
</ html>

8. v-bind.prop简写

v-bind指令有一个特殊的修饰符---.prop。你可以在文档中查看具体用法。我自己从没使用过,暂时也想不到在什么时候使用。

现在有一个简写方式,对于v-bind:someProperty.prop="foo", 可以写成.someProperty="foo"

Vue@2.5.22中:

<template>
   <div>
     <div v-bind:textContent.prop="&#39;Important text content&#39;" />
     <! - 简写版本 ->
     <div: textContent.prop="&#39;Important text content&#39;" />
   </ div>
</ template>

Vue@2.6.0:

<template>
  <div .textContent="&#39;Important text content&#39;" />
</template>

9. 支持自定义toString()

规则很简单:如果重写了对象的toString()方法,显示的时候,Vue将使用它,而不是JSON.stringify()

举例:

/ * TestComponent.vue * /
<template>
   <div>
     {{message}}
   </ div>
</ template>
<script>
export default {
   data () {
     return {
       message: {
         value: &#39;qwerty&#39;,
         toString () {
           return &#39;Hello Habr!&#39;;
         },
       },
     };
   },
};
</ script>

Vue@2.5.22中显示:

{ "value": "qwerty" }

Vue@2.6.0:

Hello Habr!

10. v-for和可迭代对象

在新版本中,v-for可以遍历任何实现了iterable协议的对象,比如Map, Set

2.X版本中,Map和Set, 不支持数据响应。

举例:

/ * TestComponent.vue * /
<template>
   <div>
     <div
       v-for="item in items"
       :key="item"
     >
       {{item}}
     </ div>
   </ div>
</ template>
<script>
export default {
   data () {
     return {
       items: new Set([4, 2, 6]),
     };
   },
};
</ script>

评论 抢沙发

表情
  1. #1

    来自天津南开的用户 5天前
    大神

  2. #2

    来自四川成都的用户 12天前
    涨知识了

  3. #3

    来自福建福州的用户 13天前
    继续讲撒 这个东西挺好玩啊