使用异步组件优化Vue应用程序的性能

2020-06-16 05:45:20易采站长站整理

{ msg: 'More Fancy', price: 109.99 },
{ msg: 'Extreme', price: 3.00 },
{ msg: 'Super Shirt', price: 109.99 },
{ msg: 'Epic Shirt', price: 3.00 },
],
shoppingList: [],
show: false
})
}
</script>
<style>
#checkout {
background-color:#e55242;
color:white;
margin-left: 10px;
}
</style>

在此文件中,我们显示一个带有商品数量的购物车图标。商品是从

items
数组中提取的。如果单击项目的
Buy
按钮,将会调用
addItem
方法,该方法会将相关商品push到
shoppingList
数组中。从而增加购物车的总数。

我们还在页面中添加了一个

Checkout
按钮:


<Button @click="show = true" id="checkout">Checkout</Button>

当用户点击这个按钮,我们设置的参数

show
true
true
是非常重要对于有通过条件地加载我们的异步组件。

在接下来的几行中,您可以找到

v-if
的声明,这个语句仅用来显示我们
checkout
组件的
<div>
,但是我们只想在用户点击
Checkout
按钮时显示结账组件,我们该怎么办?

这里我们将

checkout
组件在
components
选项里异步加载。这里
v-bind
将参数传递给组件。正如你看的的这样,创建条件异步组件是很容易的:


<div v-if="show">
<checkout v-bind:shoppingList="shoppingList"></checkout>
</div>

让我们快速

Checkout
组件添加下面的代码在
src/components/Checkout.vue
里:


<template>
<Card title="Checkout Items" key="checkout">
<p v-for="(k, i) in this.shoppingList" :key="i">
Item: {{items[Number(k)].msg}} for ${{items[Number(k)].price}}
</p>
</Card>
</template>

<script>
import { Card } from 'ant-design-vue';

export default {
props: ['shoppingList'],
components: {
Card
},
data: () => ({
items: [
{ msg: 'First Product', price: 9.99 },