Vue.js 2.6尝鲜

栏目: JavaScript · 发布时间: 5年前

内容简介:昨天Vue 2.6 "Macross" 发布了,同时也是Vuejs五周年~在这篇文章中,将会介绍新版本的新特性, 比如这是一个比较重大的改变,包含的有:
Vue.js 2.6尝鲜

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

在这篇文章中,将会介绍新版本的新特性, 比如 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. 从服务器下载数据

在新的升级版本中, 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('fetchItem');
     },
   },
};
</ script>
复制代码

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

/ * 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会产生一个没有位置的错误描述。新版本中会展示这个错误出现在哪里,比如:

<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 ('Another Error');
     },
   },
   async mounted () {
     await this.$nextTick ();
	 throw new Error ('Some Error');
   },
};
</ 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 '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中:

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

Vue@2.6.0:

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

9. 支持自定义toString()

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

举例:

/ * TestComponent.vue * /
<template>
   <div>
     {{message}}
   </ div>
</ template>
<script>
export default {
   data () {
     return {
       message: {
         value: 'qwerty',
		 toString () {
           return 'Hello Habr!';
         },
       },
     };
   },
};
</ 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>
复制代码
Vue.js 2.6尝鲜

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

搜索模式

搜索模式

Peter Morville、Jeffery Callender / 蒋彬 / 电子工业出版社 / 2010-10 / 35.00元

本书是信息架构领域创始人彼得•莫维里的又一力作,全书详尽剖析了10种搜索模式,告诉读者如何为不同情境设计搜索功能,涉及互联网、电子商务、企业、手机、社交和实时搜索等不同平台和领域。每种搜索模式均配以大量案例,并结合了作者自身的经验,因此更富实用性和实战性。书中遍布作者对于搜索模式的探索和思考,既适合对未来的搜索进行前瞻性的探讨,也能够指导当前进行中的项目。一起来看看 《搜索模式》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换