前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Vue 2.6尝鲜

Vue 2.6尝鲜

作者头像
前端知否
发布2020-03-23 17:50:07
6530
发布2020-03-23 17:50:07
举报
文章被收录于专栏:前端知否前端知否

昨天Vue 2.6 "Macross" 发布了,同时也是Vuejs五周年~

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

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

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

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

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

代码语言:javascript
复制
<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>

现在是这样的:

代码语言:javascript
复制
<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>

默认插槽:

代码语言:javascript
复制
<template>
   <! - v-slot is used directly on the parent ->
   <TestComponent v-slot="{message}">
     <div>
       {{`Default slot with message: ${message}`}}
     </ div>
   </ TestComponent>
</ template>

具名插槽:

代码语言:javascript
复制
<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中:

代码语言:javascript
复制
<div v-bind="{ [key]: value }"></div>
<div v-on="{ [event]: handler }"></div>

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

  • 不是所有人都知道在 v-bind/v-on中可以使用动态变量名
  • vue-template-compiler 生成了低效的代码
  • v-slot没有类似的使用对象的语法

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

代码语言:javascript
复制
<div v-bind:[key]="value"></div>
<div v-on:[event]="handler"></div>

举个例子:

代码语言:javascript
复制
<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)创建,如下:

代码语言:javascript
复制
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。

代码语言:javascript
复制
<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('fetchItem');
     },
   },
};
</ script>

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

代码语言:javascript
复制
/ * Simplified entry-server.js * /
import {createApp} from './app';
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会产生一个没有位置的错误描述。新版本中会展示这个错误出现在哪里,比如:

代码语言:javascript
复制
<template>
  <div>
    <template key="test-key">
      {{ message }}
    </template>
  </div>
</template>

vue-template-compiler@2.5.22中:

代码语言:javascript
复制
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中:

代码语言:javascript
复制
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可以在生命周期方法钩子和事件方法中捕捉到异步错误异常。比如:

代码语言:javascript
复制
/ * TestComponent.vue * /
<template>
   <div @click="doSomething()">
     Some message
   </ div>
</ template>
<script>
export default {
   methods: {
     async doSomething () {
       await this.$nextTick ();
       throw new Error ('Another Error');
     },
   },
   async mounted () {
     await this.$nextTick ();
     throw new Error ('Some Error');
   },
};
</ script>

mount后错误:

代码语言:javascript
复制
[Vue warn]: Error in mounted hook (Promise/async): "Error: Some Error"

点击事件后错误:

代码语言:javascript
复制
[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)

举例:

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

8. v-bind.prop简写

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

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

Vue@2.5.22中:

代码语言:javascript
复制
<template>
   <div>
     <div v-bind:textContent.prop="'Important text content'" />
     <! - 简写版本 ->
     <div: textContent.prop="'Important text content'" />
   </ div>
</ template>

Vue@2.6.0:

代码语言:javascript
复制
<template>
  <div .textContent="'Important text content'" />
</template>

9. 支持自定义toString()

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

举例:

代码语言:javascript
复制
/ * TestComponent.vue * /
<template>
   <div>
     {{message}}
   </ div>
</ template>
<script>
export default {
   data () {
     return {
       message: {
         value: 'qwerty',
         toString () {
           return 'Hello Habr!';
         },
       },
     };
   },
};
</ script>

Vue@2.5.22中显示:

代码语言:javascript
复制
{ "value": "qwerty" }

Vue@2.6.0:

代码语言:javascript
复制
Hello Habr!

10. v-for和可迭代对象

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

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

举例:

代码语言:javascript
复制
/ * 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>
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-02-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 前端知否 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. Scoped slots(作用域插槽)的新语法
  • 2. 动态参数指令
  • 3. 使用Vue.observable()创建一个响应对象
  • 4. server端获取数据
  • 5. 改进的错误输出
  • 6. 捕捉异步错误
  • 7. ESM 浏览器中的新版构建
  • 8. v-bind.prop简写
  • 9. 支持自定义toString()
  • 10. v-for和可迭代对象
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档