Home  >  Article  >  Web Front-end  >  25 Vue tips worth knowing, it turns out they can still be used in this way!

25 Vue tips worth knowing, it turns out they can still be used in this way!

青灯夜游
青灯夜游forward
2022-05-20 10:49:452567browse

This article summarizes and compiles 25 Vue tips. It took me so long to learn how to use them. Now I share them with you. I hope they will be helpful to everyone and make programming life easier. !

25 Vue tips worth knowing, it turns out they can still be used in this way!

# Learning to be a better Vue developer isn’t always about big concepts that take time and effort to master. Knowing some tips and tricks can make your programming life easier - without a lot of repetitive work.

In the past few years of developing with Vue, I have learned many useful techniques. Some are tricky, some you use almost every day, and some are more advanced - but they're all useful. (Learning video sharing: vue video tutorial)

1. Limit a prop to a list of types

A prop type can be restricted to a specific set of values ​​using the validator option in the prop definition.

export default {
  name: 'Image',
  props: {
    src: {
      type: String,
    },
    style: {
      type: String,
      validator: s => ['square', 'rounded'].includes(s)
    }
  }
};

This verification function accepts a prop and returns true or false if the prop is valid or invalid.

When simply passing in true or false to control certain conditions cannot meet the needs, I usually use this method.

Button type or warning type (info, success, danger, warning) are the most common usage. Color is also a great use.

2. Default content and extension points

Slots in Vue can have default content, which allows us to make products that are easier to use. s component.

<button class="button" @click="$emit(&#39;click&#39;)">
  <slot>
    <!-- Used if no slot is provided -->
    Click me
  </slot>
</button>

My favorite way to use default slots is to use them to create extension points.

We can take any part of the component, encapsulate it in a slot, and outside we can overwrite that part of the component with whatever we want. By default, it will still work the same way, but it will give you more options

<template>
  <button class="button" @click="$emit(&#39;click&#39;)">
    <slot>
      <div class="formatting">
        {{ text }}
      </div>
    </slot>
  </button>
</template>

Now we can use this component in many different ways. Simple, default way, or custom way.

<!-- Uses default functionality of the component -->
<ButtonWithExtensionPoint text="Formatted text" />

<ButtonWithExtensionPoint>
  <div class="different-formatting">
    Do something a little different here
  </div>
</ButtonWithExtensionPoint>

3. Use quotes to listen to nested properties

You may not know this, we can easily listen directly by using quotes Nested values:

watch {
  &#39;$route.query.id&#39;() {
    // ...
  }
}

4. Know when to use <span style="font-size: 18px;">v-if</span> (and when to avoid it )

Instead of using v-if, sometimes v-show is used instead, which will have higher performance.

<ComplicatedChart v-show="chartEnabled" />

When v-if is opened or closed, it will create and completely destroy the element. Instead, v-show will create the element and leave it there, hiding it by setting its style to display: none.

If the component you want to switch has a high rendering cost, this will be more efficient.

On the other hand, if you don't need to execute the expensive component immediately, you can use v-if so that it will skip rendering it and make the page load faster. .

5. Abbreviation for a single scoped slot (no template tag required)

Scopeed slots are very interesting, but for use They, you also have to use a lot of template tags.

Fortunately, there is a shorthand that lets us get away from it, but only if we use a single scope slot.

Normal writing:

<DataTable>
  <template #header="tableAttributes">
    <TableHeader v-bind="tableAttributes" />
  </template>
</DataTable>

Not used template:

<DataTable #header="tableAttributes">
  <TableHeader v-bind="tableAttributes" />
</DataTable>

Simple, straightforward, and amazing.

6. Conditionally render slots

Let's first look at how to do it, and then discuss why we want to hide the slot.

Every Vue component has a special $slots object that contains all your slots. The default slot key is default, and any named slot uses its name as the key.

const $slots = {
  default: <default slot>,
  icon: <icon slot>,
  button: <button slot>,
};

But this $slots object only applies to the slots of the component, not every defined slot.

Take this component that defines several slots, including several named slots.

<!-- Slots.vue -->
<template>
  <div>
    <h2>Here are some slots</h2>
    <slot />
    <slot name="second" />
    <slot name="third" />
  </div>
</template>

If we only apply one slot to a component, then only that slot will show up in our $slots object.

<template>
  <Slots>
    <template #second>
      This will be applied to the second slot.
    </template>
  </Slots>
</template>
$slots = { second: <vnode> }

We can use this in our components to detect which slots have been applied to the component, for example, by hiding the slot's wrapping element.

<template>
  <div>
    <h2>A wrapped slot</h2>
    <div v-if="$slots.default" class="styles">
      <slot />
    </div>
  </div>
</template>

Now, the wrapper div to which the style is applied will only be rendered if we fill this slot with something.

If you don't use v-if, you will get an empty unnecessary div if there is no slot. Depending on the style of the div, this may mess up our layout and make the interface look weird.

那么,为什么我们希望能够有条件地渲染插槽呢?

使用条件插槽的主要原因有三个:

  • 当使用封装的div来添加默认样式时
  • 插槽是空的
  • 如果我们将默认内容与嵌套槽相结合

例如,当我们在添加默认样式时,我们在插槽周围添加一个div:

<template>
  <div>
    <h2>This is a pretty great component, amirite?</h2>
    <div class="default-styling">
      <slot >
    </div>
    <button @click="$emit(&#39;click&#39;)">Click me!</button>
  </div>
</template>

然而,如果父组件没有将内容应用到该插槽中,我们最终会在页面上渲染出一个空的div

<div>
  <h2>This is a pretty great component, amirite?</h2>
  <div class="default-styling">
    <!-- 槽中没有内容,但这个div 仍然被渲染。糟糕 -->
  </div>
  <button @click="$emit(&#39;click&#39;)">Click me!</button>
</div>

解决方法就是像上面讲的一样,多个条件判断,就行啦。

7、如何监听一个插槽的变化

有时我们需要知道插槽内的内容何时发生了变化。

<!-- 可惜这个事件不存在 -->
<slot @change="update" />

不幸的是,Vue没有内置的方法让我们检测这一点。

然而,我的朋友Austin想出了一个非常干净的方法,使用MutationObserver来做这件事。

MutationObserver接口提供了监视对DOM树所做更改的能力。它被设计为旧的Mutation Events功能的替代品,该功能是DOM3 Events规范的一部分。

export default {
  mounted() {
    // 当有变化时调用`update`
    const observer = new MutationObserver(this.update);

    // 监听此组件的变化
    observer.observe(this.$el, {
      childList: true,
      subtree: true
    });
  }
};

这个涉及的内容还是很多的,后面会单独出一篇文章来讲,记得关注刷碗智的公众号 哦

8、将局部和全局的 <span style="font-size: 18px;">style</span>混合在一起

通常情况下,在处理样式时,我们希望它们能被划分到一个单独的组件中。

<style scoped>
  .component {
    background: green;
  }
</style>

不过,如果需要的话,也可以添加一个非作用域样式块来添加全局样式

<style>
  /* 全局 */
  .component p {
    margin-bottom: 16px;
  }
</style>

<style scoped>
  /* 在该组件内有效 */
  .component {
    background: green;
  }
</style>

但要小心,全局样式是危险的,难以追踪。但有时,它们是一个完美的逃生舱口,正是你所需要的。

9、重写子组件的样式--正确的方法

Scoped CSS在保持内容整洁方面非常棒,而且不会将样式引入应用的其他组件中。

但有时你需要覆盖一个子组件的样式,并跳出这个作用域。

Vue有一个 deep 选择器:

<style scoped>
.my-component >>> .child-component {
  font-size: 24px;
}
</style>

注意:如果你使用像SCSS这样的CSS预处理器,你可能需要使用/deep/来代替。

10、用上下文感知组件创造魔法

**上下文感知组件(context-aware)**是“魔法的”,它们自动适应周围发生的事情,处理边缘情况、状态共享等等。

有3种主要的 context-aware ,但 Configuration 是我最感兴趣的一种。

1)状态共享

当你把一个大的组件分解成多个小的组件时,它们往往仍然需要共享状态。

我们可以在 "幕后 "做这些工作,而不是把这些工作推给使用者。

我们一般会把 Dropdown 组件分解成 Select 和 Option 组件,这样会获得更多的灵活性。但是为了方便使用,Select 和Option组件彼此共享 selected 状态。

<!-- 为简单起见,作为一个单一组件使用 -->
<Dropdown v-model="selected" :options="[]" />

<!-- 分多个组件,更灵活 -->
<Select v-model="selected">
  <Option value="mustard">Mustard</Option>
  <Option value="ketchup">Ketchup</Option>
  <div class="relish-wrapper">
    <Option value="relish">Relish</Option>
  </div>
</Select>

2) Configuration

有时,一个组件的行为需要根据应用程序的其他部分的情况来改变。这通常是为了自动处理边缘情况,否则处理起来会很烦人。

一个 Popup  或 Tooltip 应该重新定位,以便它不会溢出页面。但是,如果该组件是在一个modal 内,它应该重新定位,以便它不会溢出 modal。

如果Tooltip知道它是在一个模态里面,这可以自动完成。

3)样式

创建了 context-aware的CSS,根据父级或同级元素的情况应用不同的样式。

.statistic {
  color: black;
  font-size: 24px;
  font-weight: bold;
}

.statistic + .statistic {
  margin-left: 10px;
}

CSS变量让我们更进一步,允许我们在一个页面的不同部分设置不同的值。

11、如何在Vue之外创建一个具有响应性的变量(Vue2和3)

如果你从Vue之外得到一个变量,让它具有反应性是很好的。

这样,我们就可以在computed propswatch和其他任何地方使用它,它的工作方式就像Vue中的任何其他状态一样。

如果我们使用的选项API,需要的只是将其放在组件的数据部分中:

const externalVariable = getValue();

export default {
  data() {
    return {
      reactiveVariable: externalVariable,
    };
  }
};

如果使用Vue3的组合API,可以直接使用refreactive

import { ref } from &#39;vue&#39;;

// 可以完全在Vue组件之外完成
const externalVariable = getValue();
const reactiveVariable = ref(externalVariable);

console.log(reactiveVariable.value);

使用 reactive 代替:

import { reactive } from &#39;vue&#39;;

//  可以完全在Vue组件之外完成
const externalVariable = getValue();
// reactive 只对对象和数组起作用
const anotherReactiveVariable = reactive(externalVariable);

// Access directly
console.log(anotherReactiveVariable);

如果你还在使用 Vue2,你可以使用observable而不是reactive来实现完全相同的结果。

12、v-for 中的解构

你知道可以在-vfor中使用解构吗?

<li
  v-for="{ name, id } in users"
  :key="id"
>
  {{ name }}
</li>

更广为人知的是,可以通过使用这样的元组从v-for中取出索引。

<li v-for="(movie, index) in [
  &#39;Lion King&#39;,
  &#39;Frozen&#39;,
  &#39;The Princess Bride&#39;
]">
  {{ index + 1 }} - {{ movie }}
</li>

当使用一个对象时,可以这样使用 key

<li v-for="(value, key) in {
  name: &#39;Lion King&#39;,
  released: 2019,
  director: &#39;Jon Favreau&#39;,
}">
  {{ key }}: {{ value }}
</li>

也可以将这两种方法结合起来,获取key以及属性的 index

<li v-for="(value, key, index) in {
  name: &#39;Lion King&#39;,
  released: 2019,
  director: &#39;Jon Favreau&#39;,
}">
  #{{ index + 1 }}. {{ key }}: {{ value }}
</li>

13、在指定范围内循环

v-for指令允许我们遍历数组,但它也允许我们遍历一个范围

<template>
  <ul>
    <li v-for="n in 5">Item #{{ n }}</li>
  </ul>
</template>

渲染结果:

Item #1
Item #2
Item #3
Item #4
Item #5

当我们使用带范围的v-for时,它将从1开始,以我们指定的数字结束。

14、监听你的组件中的任何东西

export default {
  computed: {
    someComputedProperty() {
      // Update the computed prop
    },
  },
  watch: {
    someComputedProperty() {
      // Do something when the computed prop is updated
    }
  }
};

我们可以监听:

  • 计算属性
  • props
  • 嵌套值

如果你使用组合API,任何值都可以被监视,只要它是一个refreactive对象。

15、窃取 prop 类型

我从一个子组件中复制 prop 类型,只是为了在一个父组件中使用它们。但我发现,偷取这些 prop 类型要比仅仅复制它们好得多。

例如,我们在这个组件中使用了一个Icon组件。

<template>
  <div>
    <h2>{{ heading }}</h2>
    <Icon
      :type="iconType"
      :size="iconSize"
      :colour="iconColour"
    />
  </div>
</template>

为了让它工作,我们需要添加正确的 prop 类型,从``Icon`组件复制。

import Icon from &#39;./Icon&#39;;
export default {
  components: { Icon },
  props: {
    iconType: {
      type: String,
      required: true,
    },
    iconSize: {
      type: String,
      default: &#39;medium&#39;,
      validator: size => [
        &#39;small&#39;,
        &#39;medium&#39;,
        &#39;large&#39;,
        &#39;x-large&#39;
      ].includes(size),
    },
    iconColour: {
      type: String,
      default: &#39;black&#39;,
    },
    heading: {
      type: String,
      required: true,
    },
  },
};

多么痛苦啊。

当 Icon 组件的 prop类型被更新时,我们肯定会忘记返回这个组件并更新它们。随着时间的推移,当该组件的 prop类型开始偏离Icon组件中的 prop 类型时,就会引入错误。

因此,这就是为什么我们要窃取组件的 prop 类型:

import Icon from &#39;./Icon&#39;;
export default {
  components: { Icon },
  props: {
    ...Icon.props,
    heading: {
      type: String,
      required: true,
    },
  },
};

不需要再复杂了。

除了在我们的例子中,我们把 icon 加在每个 prop 名称的开头。所以我们必须做一些额外的工作来实现这一点。

import Icon from &#39;./Icon&#39;;

const iconProps = {};

Object.entries(Icon.props).forEach((key, val) => {
  iconProps[`icon${key.toUpperCase()}`] = val;
});

export default {
  components: { Icon },
  props: {
    ...iconProps,
    heading: {
      type: String,
      required: true,
    },
  },
};

现在,如果Icon组件中的 prop 类型被修改,我们的组件将保持最新状态。

但是,如果一个 prop 类型从 Icon 组件中被添加或删除了呢?为了应对这些情况,我们可以使用v-bind和一个计算的 prop 来保持动态。

16、检测元素外部(或内部)的单击

有时我需要检测一个点击是发生在一个特定元素el的内部还是外部。这就是我通常使用的方法。

window.addEventListener(&#39;mousedown&#39;, e => {
  // 获取被点击的元素
  const clickedEl = e.target;
  
  if (el.contains(clickedEl)) {
   //在 "el "里面点击了
  } else {
   //在 "el "外点击了
  }
});

17、递归插槽

有一次,我决定看看我是否可以只用模板来做一个v-for组件。在这个过程中,我也发现了如何递归地使用槽。

<!-- VFor.vue -->
<template>
    <div>
        <!--  渲染第一项 -->
    {{ list[0] }}
        <!-- 如果我们有更多的项目,继续!但是不要使用我们刚刚渲染的项 -->
    <v-for
      v-if="list.length > 1"
            :list="list.slice(1)"
        />
    </div>
</template>

如果你想用作用域插槽来做这件事,只是需要一些调整

<template>
  <div>
    <!-- Pass the item into the slot to be rendered -->
    <slot v-bind:item="list[0]">
      <!-- Default -->
      {{ list[0] }}
    </slot>

    <v-for
      v-if="list.length > 1"
      :list="list.slice(1)"
    >
      <!-- Recursively pass down scoped slot -->
      <template v-slot="{ item }">
        <slot v-bind:item="item" />
      </template>
    </v-for>
  </div>
</template>

下面是这个组件的使用方法。

<template>
  <div>
    <!-- 常规列表 -->
    <v-for :list="list" />

    <!-- 加粗的项目列表 -->
    <v-for :list="list">
      <template v-slot="{ item }">
        <strong>{{ item }}</strong>
      </template>
    </v-for>
  </div>
</template>

18、组件元数据

并不是添加到一个组件的每一点信息都是状态。有时我们需要添加一些元数据,给其他组件提供更多信息。

例如,如果正在为谷歌 analytics这样的分析仪表:

25 Vue tips worth knowing, it turns out they can still be used in this way!

如果你想让布局知道每个小组件应该占多少列,你可以直接在组件上添加元数据。

export default {
  name: &#39;LiveUsersWidget&#39;,
  // ? 只需将其作为一个额外的属性添加
  columns: 3,
  props: {
    // ...
  },
  data() {
    return {
      //...
    };
  },
};
export default {
  name: &#39;LiveUsersWidget&#39;,
  // ?  只需将其作为一个额外的属性添加
  columns: 3,
  props: {
    // ...
  },
  data() {
    return {
      //...
    };
  },
};

你会发现这个元数据是组件上的一个属性。

import LiveUsersWidget from &#39;./LiveUsersWidget.vue&#39;;
const { columns } = LiveUsersWidget;

我们也可以通过特殊的$options属性从组件内部访问元数据。

export default {
  name: &#39;LiveUsersWidget&#39;,
  columns: 3,
  created() {
    // ? `$options` contains all the metadata for a component
    console.log(`Using ${this.$options.metadata} columns`);
  },
};

只要记住,这个元数据对组件的每个实例都是一样的,而且不是响应式的。

这方面的其他用途包括(但不限于):

  • 保持单个组件的版本号
  • 用于构建工具的自定义标志,以区别对待组件
  • 在计算属性、数据、watch 等之外为组件添加自定义功能
  • 其它

19、多文件单文件组件

这是**SFC(单文件组件)**的一点已知功能。

可以像常规HTML文件一样导入文件:

<template src="./template.html"></template>
<script src="./script.js"></script>
<style scoped src="./styles.css"></style>

如果你需要分享样式、文件或其他任何东西,这可能会非常方便。

20、可重复使用的组件并不是你所想的那样

可重复使用的组件不一定是大的或复杂的东西。

我经常让小的和短的组件可以重复使用。

因为我没有到处重写这段代码,所以更新它变得更加容易,而且我可以确保每个OverflowMenu的外观和工作方式都完全一样--因为它们是一样的!"。

<!-- OverflowMenu.vue -->
<template>
  <Menu>
    <!-- 添加一个自定义按钮来触发我们的菜单   -->
    <template #button v-slot="bind">
      <!-- 使用bind来传递click处理程序、a11y 属性等 -->
      <Button v-bind="bind">
        <template #icon>
          <svg src="./ellipsis.svg" />
        </template>
      </Button>
    </template>
  </Menu>
</template>

在这里,我们采用了一个菜单组件,但在触发它的按钮上添加了一个 ellipsis 图标。(省略号)的图标来触发它的打开。

这似乎不值得把它做成一个可重复使用的组件,因为它只有几行。难道我们就不能在每次要使用这样的菜单时添加图标吗?

但是这个OverflowMenu将被使用几十次,现在如果我们想更新图标或它的行为,我们可以非常容易地做到。而且,使用它也更简单了。

21、从组件外部调用一个方法

我们可以从一个组件的外部通过给它一个 ref 用来调用一个方法。

<!-- Parent.vue -->
<template>
  <ChildComponent ref="child" />
</template>
// Somewhere in Parent.vue
this.$refs.child.method();

再解释一下这个问题。

有时候,“最佳实践”并不适用于你正在做的事情,你需要一个像这样的逃生口。

通常情况下,我们使用 props  和 events 在组件之间进行交流。props 被下发到子组件中,而events 被上发到父组件中。

<template>
  <ChildComponent
    :tell-me-what-to-do="someInstructions"
    @something-happened="hereIWillHelpYouWithThat"
  />
</template>
// Child.vue
export default {
  props: [&#39;trigger&#39;],
  watch: {
    shouldCallMethod(newVal) {
      if (newVal) {
        // Call the method when the trigger is set to `true`
        this.method();
      }
    }
  }
}

这可以正常工作,但只能在第一次调用时使用。如果您需要多次触发此操作,则必须进行清理并重置状态。逻辑是这样的

  • 父组件将 true 传递给触发器 prop
  • Watch 被触发,然后 Child 组件调用该方法
  • 子组件发出一个事件,告诉父组件该方法已被成功触发
  • Parent组件将 trigger 重置为 false,所以我们可以从头再来一次

相反,如果我们在子组件上设置一个 ref,我们可以直接调用该方法:

<!-- Parent.vue -->
<template>
  <ChildComponent ref="child" />
</template>
// Somewhere in Parent.vue
this.$refs.child.method();

是的,我们打破了 “props down, events up"” 的规则,我们打破了封装,但是这样做更清晰,更容易理解,所以是值得的

有时,"最好的 "解决方案最终会成为最糟糕的解决方案。

22、监听数组和对象

使用 watcher 最棘手的部分是,有时它似乎不能正确触发。

通常,这是因为我们试图监听数组或对象,但没有将deep设置为true

export default {
  name: &#39;ColourChange&#39;,
  props: {
    colours: {
      type: Array,
      required: true,
    },
  },
  watch: {
    // 使用对象语法,而不仅仅是方法
    colours: {
      // 这将让Vue知道要在数组内部寻找
      deep: true,

      handler()
        console.log(&#39;The list of colours has changed!&#39;);
      }
    }
  }
}

使用Vue 3的API会是这样的:

watch(
  colours,
  () => {
    console.log(&#39;The list of colours has changed!&#39;);
  },
  {
    deep: true,
  }
);

23、用Vue Router进行深度链接

我们可以在URL中存储(一点)状态,允许我们直接跳到页面上的一个特定状态。

例如,你加载一个已经选择了日期范围过滤器的页面:

someurl.com/edit?date-range=last-week

这对于应用中用户可能共享大量链接的部分来说是非常棒的,对于服务器渲染的应用,或者在两个独立的应用之间通信的信息比普通链接通常提供的更多。

我们可以存储过滤器、搜索值、模态框是打开还是关闭,或者在列表的哪个位置滚动以完美地实现无限分页。

使用 vue-router 获取查询参数是这样工作的(这也适用于大多数Vue框架,如Nuxt和Vuepress):

const dateRange = this.$route.query.dateRange;

为了改变它,我们使用 RouterLink 组件并更新 query

<RouterLink :to="{
  query: {
    dateRange: newDateRange
  }
}">

24、<span style="font-size: 18px;">template</span> 标签的另一个用途

template 标签可以在模板中的任何地方使用,以更好地组织代码。

我喜欢用它来简化v-if逻辑,有时也用v-for

在这个例子中,我们有几个元素都使用同一个v-if条件。

<template>
  <div class="card">
    <img  src="imgPath" / alt="25 Vue tips worth knowing, it turns out they can still be used in this way!" >
    <h3>
      {{ title }}
    </h3>
    <h4 v-if="expanded">
      {{ subheading }}
    </h4>
    <div
      v-if="expanded"
      class="card-content"
    >
      <slot />
    </div>
    <SocialShare v-if="expanded" />
  </div>
</template>

这有点笨拙,而且一开始并不明显,一堆这样的元素被显示和隐藏在一起。在一个更大、更复杂的组件上,这可能是一个更糟糕的情况

但我们能优化它。

我们可以使用 template 标签来分组这些元素,并将 v-if 提升到模板 template  本身。

<template>
  <div class="card">
    <img  src="imgPath" / alt="25 Vue tips worth knowing, it turns out they can still be used in this way!" >
    <h3>
      {{ title }}
    </h3>
    <template v-if="expanded">
      <h4>
        {{ subheading }}
      </h4>
      <div class="card-content">
        <slot />
      </div>
      <SocialShare />
    </template>
  </div>
</template>

现在看起来就更容易理解,而且它在做什么,一目了然。

25、处理错误(和警告)的更好方法

我们可以为Vue中的错误和警告提供一个自定义处理程序。

// Vue 3
const app = createApp(App);
app.config.errorHandler = (err) => {
  alert(err);
};

// Vue 2
Vue.config.errorHandler = (err) => {
  alert(err);
};

像 Bugsnag 和 Rollbar 这样的错误跟踪服务,可以钩住这些处理程序来记录错误,但你也可以用它们来更优雅地处理错误,以获得更好的用户体验。

For example, instead of the app crashing directly if an error is not handled, you can show a full error screen and let the user refresh or try something else.

In Vue3, the error handler can only handle template and watcher errors, but Vue2’s error handler can catch almost all errors . The warning handlers in both versions only work during the development phase.

(Learning video sharing: web front-end development, Basic programming video)

The above is the detailed content of 25 Vue tips worth knowing, it turns out they can still be used in this way!. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete