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

Introduction to new features of Vue.js 2.5

Jan 03, 2018 pm 01:20 PM
javascript vue.js introduce

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1225
24
Detailed introduction to what wapi is Detailed introduction to what wapi is Jan 07, 2024 pm 09:14 PM

Users may have seen the term wapi when using the Internet, but for some people they definitely don’t know what wapi is. The following is a detailed introduction to help those who don’t know to understand. What is wapi: Answer: wapi is the infrastructure for wireless LAN authentication and confidentiality. This is like functions such as infrared and Bluetooth, which are generally covered near places such as office buildings. Basically they are owned by a small department, so the scope of this function is only a few kilometers. Related introduction to wapi: 1. Wapi is a transmission protocol in wireless LAN. 2. This technology can avoid the problems of narrow-band communication and enable better communication. 3. Only one code is needed to transmit the signal

Detailed explanation of whether win11 can run PUBG game Detailed explanation of whether win11 can run PUBG game Jan 06, 2024 pm 07:17 PM

Pubg, also known as PlayerUnknown's Battlegrounds, is a very classic shooting battle royale game that has attracted a lot of players since its popularity in 2016. After the recent launch of win11 system, many players want to play it on win11. Let's follow the editor to see if win11 can play pubg. Can win11 play pubg? Answer: Win11 can play pubg. 1. At the beginning of win11, because win11 needed to enable tpm, many players were banned from pubg. 2. However, based on player feedback, Blue Hole has solved this problem, and now you can play pubg normally in win11. 3. If you meet a pub

Detailed introduction to whether i5 processor can install win11 Detailed introduction to whether i5 processor can install win11 Dec 27, 2023 pm 05:03 PM

i5 is a series of processors owned by Intel. It has various versions of the 11th generation i5, and each generation has different performance. Therefore, whether the i5 processor can install win11 depends on which generation of the processor it is. Let’s follow the editor to learn about it separately. Can i5 processor be installed with win11: Answer: i5 processor can be installed with win11. 1. The eighth-generation and subsequent i51, eighth-generation and subsequent i5 processors can meet Microsoft’s minimum configuration requirements. 2. Therefore, we only need to enter the Microsoft website and download a "Win11 Installation Assistant" 3. After the download is completed, run the installation assistant and follow the prompts to install Win11. 2. i51 before the eighth generation and after the eighth generation

Introducing the latest Win 11 sound tuning method Introducing the latest Win 11 sound tuning method Jan 08, 2024 pm 06:41 PM

After updating to the latest win11, many users find that the sound of their system has changed slightly, but they don’t know how to adjust it. So today, this site brings you an introduction to the latest win11 sound adjustment method for your computer. It is not difficult to operate. And the choices are diverse, come and download and try them out. How to adjust the sound of the latest computer system Windows 11 1. First, right-click the sound icon in the lower right corner of the desktop and select "Playback Settings". 2. Then enter settings and click "Speaker" in the playback bar. 3. Then click "Properties" on the lower right. 4. Click the "Enhance" option bar in the properties. 5. At this time, if the √ in front of "Disable all sound effects" is checked, cancel it. 6. After that, you can select the sound effects below to set and click

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

What is Dogecoin What is Dogecoin Apr 01, 2024 pm 04:46 PM

Dogecoin is a cryptocurrency created based on Internet memes, with no fixed supply cap, fast transaction times, low transaction fees, and a large meme community. Uses include small transactions, tips, and charitable donations. However, its unlimited supply, market volatility, and status as a joke coin also bring risks and concerns. What is Dogecoin? Dogecoin is a cryptocurrency created based on internet memes and jokes. Origin and History: Dogecoin was created in December 2013 by two software engineers, Billy Markus and Jackson Palmer. Inspired by the then-popular "Doge" meme, a comical photo featuring a Shiba Inu with broken English. Features and Benefits: Unlimited Supply: Unlike other cryptocurrencies such as Bitcoin

Detailed information on the location of the printer driver on your computer Detailed information on the location of the printer driver on your computer Jan 08, 2024 pm 03:29 PM

Many users have printer drivers installed on their computers but don't know how to find them. Therefore, today I bring you a detailed introduction to the location of the printer driver in the computer. For those who don’t know yet, let’s take a look at where to find the printer driver. When rewriting content without changing the original meaning, you need to The language is rewritten to Chinese, and the original sentence does not need to appear. First, it is recommended to use third-party software to search. 2. Find "Toolbox" in the upper right corner. 3. Find and click "Device Manager" below. Rewritten sentence: 3. Find and click "Device Manager" at the bottom 4. Then open "Print Queue" and find your printer device. This time it is your printer name and model. 5. Right-click the printer device and you can update or uninstall it.

PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions Feb 25, 2024 am 11:15 AM

PyCharm is a powerful Python integrated development environment with rich functions and tools that can greatly improve development efficiency. Among them, the replacement function is one of the functions frequently used in the development process, which can help developers quickly modify the code and improve the code quality. This article will introduce PyCharm's replacement function in detail, combined with specific code examples, to help novices better master and use this function. Introduction to the replacement function PyCharm's replacement function can help developers quickly replace specified text in the code

See all articles