Home > Web Front-end > JS Tutorial > Introduction to new features of Vue.js 2.5

Introduction to new features of Vue.js 2.5

小云云
Release: 2018-01-03 13:20:31
Original
1693 people have browsed it

Vue 2.5 Level E has been released. It has made many corresponding improvements and bug fixes based on the original 2.x. The latest version of the 2.5 series is currently 2.5.2. This article mainly shares with you the new Vue.js 2.5 Features, hope it helps everyone.

TypeScript is a free and open source programming language developed by Microsoft. It is a superset of JavaScript and essentially adds optional static typing and class-based object-oriented programming to the language. In October 2012, Microsoft released the first public version of TypeScript. On June 19, 2013, Microsoft released the official version of TypeScript 0.9. So far, TypeScript has developed to version 2.x

Installing TypeScript

There are two main ways to install TypeScript:

Install through npm (Node.js package manager)

Install the Visual Studio plug-in for TypeScript

Note: Visual Studio2016 and Visual Studio 2013 Update 2 include TypeScript by default. The command for npm installation is as follows:

npm install -g typescript

Create TypeScript file

Create a new greeter.ts file in the editor and enter the following JavaScript code:

function greeter(person) {
 return "Hello, " + person;
}
var user = "Jane User";
document.body.innerHTML = greeter(user);
Copy after login

The above code directly outputs "hello Jane User".

Compile code

Run the TypeScript compiler on the command line to compile the code:

tsc greeter.ts

Run TypeScript web program

Now enter the following code in greeter.html:

<!DOCTYPE html>
<html>
 <head><title>TypeScript Greeter</title></head>
 <body>
  <script src="greeter.js"></script>
 </body>
</html>
Copy after login

Open greeter.html in the browser to run the first TypeScript web application demo!

New features of Vue.js 2.5

Vue 2.5 Level E has been released. It has made many corresponding improvements and bug fixes based on the original 2.x. It is currently the latest version of the 2.5 series is 2.5.2. If readers want to fully understand the content of Vue 2.5, they can get a detailed introduction by viewing the Vue 2.5 release notes. Based on the official introduction and information collected online, this 2.5 version mainly makes the following improvements:

Better TypeScript integration
Better error handling
Better support for single Functional components in file components
Environment-independent server-side rendering
Readers can view the original introduction through the following link:

TypeScript declaration improvement

further improve Vue type declarations for canonical usage (#6391) db138e2

Error handling and reporting

improve error handling with new errorCaptured hook b3cd9bc [Details]

improve template expression error message e38d006, closes #6771

improve option type checks b7105ae

functional component

compiled templates for functional component support ea0d227

scoped CSS support for functional components 050bb33

Server-side rendering

renderToString now returns a Promise if no callback is passedf881dd1, closes #6160

add shouldPrefetch option (same signature as shouldPreload) 7bc899c, closes #5964

auto-remove initial state embed script if in production (#6763) 2d32b5d, closes #6761

now ships an environment-agnostic build of the server renderer in vue-server-renderer/basic .jsc5d0fa0 Details

TypeScript improvements

Since the release of Vue2.0, developers have been making requests for better integration of TypeScript. Since then we have included official TypeScript type declarations for most core libraries (vue, vue-routervuex). However, when using the out-of-the-box Vue API, current integration is lacking. For example: TypeScript cannot easily infer the this type in the default object-based API used by Vue. In order to make our Vue code work better with TypeScript, we need to use the vue-class-component decorator, which allows us to write Vue components using class-based syntax.

For users who like class-based APIs, this may be good, but it is still a bit insufficient. Just for type judgment, users have to use different APIs. This also makes migrating existing Vue codebases to TypeScript more difficult.

Earlier this year, TypeScript introduced some new features that allow TypeScript to better understand object literal-based APIs, which also makes it more possible to improve Vue’s type declarations. Daniel Rosenwasser from the TypeScript team launched an ambitious PR plan. After using TypeScript, you will have the following benefits:

Correct type inference for this when using the default Vue API. Also works in single file components!

Type inference of props configured based on component props.

What’s more, these improvements will benefit native JavaScript users too! , if you are using VSCode and have installed the excellent Vetur extension, when using native JavaScript in Vue components, you will get very complete auto-completion prompts and even type prompts! This is because vue-language-server, the internal package that analyzes Vue components, can leverage the TypeScript compiler to extract more information about your code. In addition, any editor that supports the language service protocol can use vue-language-server to provide similar functionality.

Note: Note: TypeScript users should also update the following packages to the latest versions to be compatible with type declarations: vue-router, vuex, vuex-router-sync and vue-class-component.

错误提示

在2.4及更早版本中,通常使用全局 config.errorHandleroption 来处理应用程序中的意外错误。当然,还可以使用renderError 组件选项来处理渲染函数中的错误。

而在新版本中,vue引入了errorCaptured 钩子,具有此钩子的组件捕获其子组件树(不包括其自身)中的所有错误(不包括在异步回调中调用的那些)。这和React的思想是一致的。

要利用 errorCaputerd,可以封装一个通用组件,来包含其他的业务组件,来捕获业务组件内的异常,并做对应的展示处理。下面列一个官方给的简单示例,封装一个通用组件(ErrorBoundary)来包含和处理其他业务组件(another component)的异常。

Vue.component('ErrorBoundary', {
 data: () => ({ error: null }),
 errorCaptured (err, vm, info) { 
 this.error = `${err.stack}\n\nfound in ${info} of component`
 return false
 },
 render (h) { 
 if (this.error) {  
  return h('pre', { style: { color: 'red' }}, this.error)
 } 
 // ignoring edge cases for the sake of demonstration
 return this.$slots.default[0]
 }
})
<error-boundary>
 <another-component />
</error-boundary>
Copy after login

errorCaputed参数传递主要有如下的特性:

如果定义了全局的 errorHandler,所有的异常还是会传递给 errorHadnler,如果没有定义
errorHandler,这些异常仍然可以报告给一个单独的分析服务。

如果一个组件上通过继承或父组件定义了多个 errorCapured 钩子函数,这些钩子函数都会收到同样的异常信息。
可以在 errorCapured 钩子内 return false 来阻止异常传播,表示:该异常已经被处理,可忽略。而且,也会阻止其他的 errorCapured 钩子函数和全局的 errorHandler 函数触发这个异常。

SFC 函数式组件

通过 vue-loader v13.3.0 或以上版本,支持在单文件组件内定义一个“函数式组件”,且支持模板编译、作用域 CSS 和 热部署等功能。

函数式组件的定义,需要在 template 标签上定义 functional 属性来声明。且模板内的表达式的执行上下文是 函数式声明上下文,所以要访问组件的属性,需要使用 props.xxx 来获取。例子见下:

<template functional>
 <p>{{ props.msg }}</p>
</template>
Copy after login

与环境无关的服务端渲染(SSR 环境)

使用 vue-server-renderer 来构建 SSR 应用时,默认是需要一个 Node.js 环境的,使得一些像 php-v8js 或 Nashorn 这样的 JavaScript 运行环境下无法运行。v2.5 中对此进行了完善,使得上述环境下都可以正常运行 SSR 应用。

在 php-v8js 和 Nashorn 中,在环境的准备阶段需要模拟 global 和 process 全局对象,并且需要单独设置 process 的环境变量。需要设置 process.env.VUE_ENV 为 “server”,设置 process.env.NODE_ENV 为 “development” 或 “production”。

另外,在 Nashorn 中,还需要用 Java 原生的 timers 为 Promise 和 settimeout 提供一个 polyfill。官方给出了一个在 php-v8js 中的使用示例,如下:

<?php
$vue_source = file_get_contents(&#39;/path/to/vue.js&#39;);
$renderer_source = file_get_contents(&#39;/path/to/vue-server-renderer/basic.js&#39;);
$app_source = file_get_contents(&#39;/path/to/app.js&#39;);
$v8 = new V8Js();
$v8->executeString('var process = { env: { VUE_ENV: "server", NODE_ENV: "production" }}; this.global = { process: process };');
$v8->executeString($vue_source);
$v8->executeString($renderer_source);
$v8->executeString($app_source);
?>
// app.js
var vm = new Vue({
 template: `<p>{{ msg }}</p>`,
 data: {
 msg: 'hello'
 }
})
// exposed by vue-server-renderer/basic.js
renderVueComponentToString(vm, (err, res) => {
 print(res)
})
Copy after login

Vue.js 这款渐进式的 JavaScript 框架自 2013 年发布至今,其简洁的语法设计、轻量快速的特点深受技术社区喜爱,在国内外都获得了非常广泛的应用及拓展,比如饿了么的开源组件库 Element UI 即是 根据Vue 开发的,而阿里巴巴的 Weex 与 Vue 也多有合作,而美团点评的mpVue也是比较出色的一款框架。

v-on 修饰符

键值 key 自动修饰符

在 Vue v2.5 之前的版本中,如果要在 v-on 中使用没有内置别名的键盘键值,要么直接使用 keyCode 当修饰符(@keyup.13=”foo”),要么需要使用 config.keyCodes 来为键值注册别名。在 v2.5中,你可以直接使用合法的键值 key 值(参考MDN中的 KeyboardEvent.key)作为修饰符来串联使用它。如下:

<input @keyup.page-down="onPageDown">
Copy after login

上述例子中,事件处理函数只会在 $event.key === ‘PageDown' 时被调用。

注意:现有键值修饰符仍然可用。在IE9中,一些键值(.esc 和 方向键的 key)不是一致的值,如果要兼容 IE9,需要按 IE9 中内置的别名来处理。

.exact 修饰符

新增了一个 .exact 修饰符,该修饰符应该和其他系统修饰符(.ctrl, .alt, .shift and .meta)结合使用,可用用来区分一些强制多个修饰符结合按下才会触发事件处理函数。如下:

<!-- 当 Alt 或 Shift 被按下也会触发处理函数 -->
<button @click.ctrl="onClick">A</button>
<!-- 只有当 Ctrl 被按下,才会触发处理函数 -->
<button @click.ctrl.exact="onCtrlClick">A</button>
Copy after login

简化 Scoped Slots 的使用

之前,如果要在 template 标签上使用 scope 属性定义一个 scoped slot,可以像下面这样定义:

<comp>
 <template scope="props">
 <p>{{ props.msg }}</p>
 </template>
</comp>
Copy after login

在 v2.5 中,scope 属性已被弃用(仍然可用,但是会爆出一个警告,就像本文文首的那样),我们使用 slot-scope 属性替代 scope 属性来表示一个 scoped slot,且 slot-scope 属性除了可以被用在 template 上,还可以用在标签元素和组件上。如下:

<comp>
 <p slot-scope="props">
 {{ props.msg }}
 </p>
</comp>
Copy after login

注意:这次的调整,表示 slot-scope 已经是一个保留属性了,不能再被单独用在组件属性上了。

Inject 新增默认值选项

本次调整中,Injections 可以作为可选配置,并且可以声明默认值。也可以用 from 来表示原属性。

export default {
 inject: {
 foo: {
  from: 'bar',
  default: 'foo'
 }
 }
}
Copy after login

与属性类似,数组和对象的默认值需要使用一个工厂函数返回。

export default {
 inject: {
 foo: {
  from: 'bar',
  default: () => [1, 2, 3]
 }
 }
}
Copy after login

相关推荐:

vue.js做出图书管理平台的详细步骤

vue.js的语法及常用指令的详解

vue.js todolist如何实现

The above is the detailed content of Introduction to new features of Vue.js 2.5. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template