44

Vue 2.6 尝鲜

 5 years ago
source link: https://mp.weixin.qq.com/s/wQdc2fcqUMZV6SR7kSPELQ?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

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

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

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

  • v-slot新指令,结合了  slot 和  slot-scope 的功能

  • scoped slots 的简写

之前在 [email protected] 中是这样使用 scoped-slots 的:

现在是这样的:

默认插槽:

具名插槽:

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

2. 动态参数指令

如果我们想在 v-bind or v-on 中使用动态变量,在 [email protected] 中:

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

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

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

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

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

举个例子:

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

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

4. 从服务器下载数据

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

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

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

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

5. 改进的错误输出

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

[email protected]中:

[email protected]中:

6. 捕捉异步错误

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

mount后错误:

点击事件后错误:

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

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

特性:

  • 在render函数中,包含HTML编译器

  • 使用ES6模块语法

  • 包含非副本代码(non-transcript)

举例:

8. v-bind.prop简写

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

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

[email protected]中:

[email protected]:

9. 支持自定义toString ()

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

举例:

[email protected]中显示:

[email protected]:

10. v-for和可迭代对象

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

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

举例:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK