Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

理解 Vue.js 中的 Mixins #5776

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 68 additions & 75 deletions TODO1/understanding-mixins-in-vue-js.md
Original file line number Diff line number Diff line change
@@ -1,77 +1,69 @@
> * 原文地址:[Understanding Mixins in Vue JS](https://blog.bitsrc.io/understanding-mixins-in-vue-js-bdcf9e02a7c1)
> * 原文作者:[Nwose Lotanna](https://medium.com/@viclotana)
> * 译文出自:[掘金翻译计划](https://github.com/xitu/gold-miner)
> * 本文永久链接:[https://github.com/xitu/gold-miner/blob/master/TODO1/understanding-mixins-in-vue-js.md](https://github.com/xitu/gold-miner/blob/master/TODO1/understanding-mixins-in-vue-js.md)
> * 译者:
> * 校对者:
> - 原文地址:[Understanding Mixins in Vue JS](https://blog.bitsrc.io/understanding-mixins-in-vue-js-bdcf9e02a7c1)
> - 原文作者:[Nwose Lotanna](https://medium.com/@viclotana)
> - 译文出自:[掘金翻译计划](https://github.com/xitu/gold-miner)
> - 本文永久链接:[https://github.com/xitu/gold-miner/blob/master/TODO1/understanding-mixins-in-vue-js.md](https://github.com/xitu/gold-miner/blob/master/TODO1/understanding-mixins-in-vue-js.md)
> - 译者:[MacTavish Lee](https://github.com/Reaper622)
> - 校对者:[Baddyo](https://github.com/Baddyo), [jilanlan](https://github.com/jilanlan)

# Understanding Mixins in Vue JS
# 理解 Vue.js 中的 Mixins

A useful introduction to Mixins in Vue, why they are important and how to use them in your workflow.
本文是针对 Vue 中的 Mixins 的实用性介绍,探讨了 Mixins 为何重要,以及如何在工作流中使用。

![Photo by [Augustine Fou](https://unsplash.com/@augustinefou?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)](https://cdn-images-1.medium.com/max/12000/0*gtfwEvDVwDgHMv7L)

## What are Mixins?
## 什么是 Mixins

Mixins in Vue JS are basically a chunk of defined logic, stored in a particular prescribed way by Vue, which can be re-used over and over to add functionality to your Vue instances and components. So Vue mixins can be shared between multiple Vue components without the need to repeat code blocks. Anyone who has used the CSS pre-processor called SASS has a good idea of mixins.
Vue JS 中的 Mixins 基本上是定义一大堆逻辑的地方,它们以 Vue 规定的特殊方式存储,它们可以反复使用来为 Vue 实例和组件添加功能。因此,Vue mixins 可以在多个 Vue 组件之间共享,而不需要重复写代码块。如果你之前用过 Sass 这个 CSS 预处理器,那么你会对 mixins 有很好的理解。

## Before you start
## 写在开始前

This post is suited for intermediate frontend developers that use Vue JS, and so being conversant with beginner concepts and installation processes is assumed. Here are a few prerequisites you should already have before you start to use Vue CLI 3 through this article.
这篇文章更适合于使用 Vue JS 开发的中级前端工程师,因此你需要先熟悉基础概念以及安装过程。在开始使用 Vue CLI 3 之前,已经掌握了这些预备知识。

You will need:
你需要:

* Node.js 10.x and above installed. You can verify if you do by running node -v in your terminal/command prompt.

* The Node Package Manager 6.7 or above (NPM) also installed.

* A code editor: Visual Studio Code is highly recommended. ([here’s why](https://blog.bitsrc.io/a-convincing-case-for-visual-studio-code-c5bcc18e1693?source=your_stories_page---------------------------))

* Vue latest version installed globally on your machine.

* Vue CLI 3.0 installed on your machine. To do this, uninstall the old CLI version first:
- 安装了 Node.js 10.x 或者更高的版本。你可以在你的终端运行 node -v 来校验你的版本。
- 已经安装了 Node Package Manager 6.7 或者更高的版本(NPM)。
- 一个代码编辑器:高度推荐 Visual Studio Code。 ([推荐理由](https://blog.bitsrc.io/a-convincing-case-for-visual-studio-code-c5bcc18e1693?source=your_stories_page---------------------------))
- 在你的设备上全局安装了 Vue 的最新版本。
- 在你的设备上安装了 Vue CLI 3.0。在安装 3.0,先卸载旧版本的 CLI 工具:

```
npm uninstall -g vue-cli
```

then install the new one:
之后安装新的版本:

```
npm install -g @vue/cli
```

OR

* Download a Vue starter project here:
或者

[**viclotana/vue-canvas**: An optimized and ready-to-use vue application with the default babel and Eslint config](https://github.com/viclotana/vue-canvas)
- 在这里下载一个 Vue 的启动项目:

* Unzip the downloaded project
[**viclotana/vue-canvas**: 一个经过优化、开箱即用的 Vue 应用、配备了默认的 Babel 和 ESlint 的配置](https://github.com/viclotana/vue-canvas)

* Navigate into the unzipped file and run the command to keep all the dependencies up-to-date:
- 解压下载的项目
- 进入到解压后的文件之后运行下面的命令来保证所有的依赖都是最新的:

```
npm install
```

## Why are Mixins important

1. With Vue mixins, you can easily adhere to the DRY principle in programming which simply ensures that you do not repeat yourself.
## 为什么 Mixins 是重要的

2. With Vue mixins, you also get a great option of flexibility, a mixin object contains options for Vue components so there is a mixing of both mixin and component options.
1. 使用 Vue mixins, 你可以轻松地在编程中遵循 DRY 原则(译者注: Don't Repeat Yourself),它会确保你不会重复自己的代码。
2. 使用 Vue mixins,你也可以变得十分的灵活,一个 mixins 对象包含有 Vue 组件的选项,所以我们可以将 mixin 与 组件混合使用。
3. Vue mixins 也是很安全的,如果你的写法恰当,那么它们是不会对超出定义范围的变更产生影响的。
4. 它们是很棒的代码复用平台。

3. Vue mixins are also safe, they do not affect changes outside their defined scope if they are well written.
> Mixins 能够灵活地实现为 Vue 组件分发可复用功能。 — 官方文档

4. They are a great platform for code reusability.
## Mixins 帮助我们解决了什么问题

> Mixins are a flexible way to distribute reusable functionalities for Vue components — Official Docs
想要充分理解 Vue 中 mixins 的重要性,有一个方式:看看在实际开发中遇到的重用问题。如果你有两个组件,二者中各有一个目的一致或功能相同的方法,就像在下面这个简单的示例中:

## The problem mixins help to solve

One way to fully understand the importance of mixins in Vue is to see the re-use problem in action. If you have two components that contains a method that does exactly the same thing or performs the exact functionality in the two components like the simple example below:

Navigate into the project folder and to the src folder and create a components directory where you can then create two components: Test.vue and Modal.vue. Copy the code below to the appropriate components respectively.
进入的你的项目文件夹之后到 src 文件夹创建一个名为 components 的目录,并在其中创建两个组件:Test.vue 和 Modal.vue。复制下面的代码到你的组件中。

```Vue
// Component 1
Expand All @@ -93,7 +85,7 @@ export default {
};
```

The component above displays a button that shows an alert modal when clicked. The second component below does exactly the same thing:
上面的组件展示了一个按钮,点击它会弹出一个警告框。第二个组件会做确切相同的功能:

```Vue
// Component 2
Expand All @@ -116,7 +108,7 @@ export default {
};
```

Your App.vue file should have the both components imported and declared exactly like it is below:
你的 App.vue 文件应该引入和声明两个组件,如下所示:

```Vue
<template>
Expand All @@ -139,18 +131,18 @@ export default {
</script>
```

So you can clearly see that we are repeating the click method code block in the both components and this is not very ideal as it is not an efficient way to handle memory resources and it also goes against the DRY principle.
至此你可以很清楚地看到,两个组件中的点击方法的代码是重复的,并且不完美之处在于这样会浪费内存资源,同时也违反了 DRY 的原则。

## Introducing Vue Mixins
## 介绍 Vue Mixins

The team at Vue has now introduced the mixins as a good solution to this problem, with mixins you can encapsulate a piece of code or functionality and then import it for use as often as you want in various components.
Vue 的团队现在已经将 mixins 作为这个问题的一个非常好的解决方案,通过 mixins 你可以封装一部分的代码或者功能,然后你可以在需要时将其引入各种组件。

## Mixin syntax
## Mixin 语法

Vue Mixin from definition to usage looks like this:
从定义到使用 Vue Mixin 的方式如下:

```Vue
// define a mixin object
// 定义一个 mixin 对象
var myMixin = {
created: function() {
this.hello();
Expand All @@ -161,7 +153,7 @@ var myMixin = {
}
}
};
// define a component that uses this mixin
// 定义一个组件来使用这个 mixin
var Component = Vue.extend({
mixins: [myMixin]
});
Expand All @@ -170,16 +162,16 @@ var component = new Component(); // => "hello from mixin!"

## Demo

You are going to use Vue mixins to rebuild the two components we initially used at the beginning of this post to illustrate the problem. To use mixins in a Vue application, you have to pass through four stages:
现在你可以用 Vue mixins 重构上文中用来例证复用问题的两个组件。在一个 Vue 应用中使用 mixins,要经过四个步骤:

* Create the mixin file.
* Import the mixin file into the needed component.
* Remove the repeated logic from said components.
* Register the mixin.
- 撞见混入文件。
- 在需要的组件中引入 mixin 文件。
- 在组件中移除重复的逻辑。
- 注册 mixin

### Creating the mixin file
### 创建 mixin 文件

A mixin file is an exportable javascript file in which the block of code or functionality to be imported and re-used in your various desired Vue components is defined. For developers like myself who like to keep things very modular, create a Mixins folder inside the src folder and then create a clickMixin.js file inside it. Copy the code below into the newly created file.
一个 mixin 文件是一个可导出的 JavaScript 文件,它内部定义了需要在所需的 Vue 组件中导入和重用的代码块和功能块。对于像我这种很喜欢让编程非常模块化的开发者,可以在 src 文件夹中创建一个 Mixins 文件夹之后在内部创建一个 clickMixin.js 文件。在新创建的文件中复制下面的代码:

```JavaScript
// src/mixins/clickMixin.js
Expand All @@ -192,22 +184,22 @@ export default {
};
```

This is the the mixin file, inside is a simple click method that pops up an alert modal. It can be any logic at all, it can have data options, computed properties and anything a Vue component can have. The possibilities are really only limited to your imagination and use case as a developer.
这就是一个 mixin 文件,其中包含了实现弹出警告框的简单的点击方法。 它也可以是任何逻辑,也可以有数据选项,计算属性和 Vue 组件可以拥有的任何东西。它的可能性仅局限于你的想象力和开发人员的用例。

### Importing the mixin file into components
### 在组件中导入 mixin 文件

Now that a mixin has been created, the next step is to inject it inside the components where it is needed: where the functionality should come to play. In our demonstration above, that would be inside the two components we already created in the beginning of this post. Import the clickMixin inside the two components with the command below:
现在一个 mixin 已经被创建了,下一步就是在需要它的组件 —— 需要弹出警告框功能的组件 —— 中注入它。在我们上面的演示中,要插入 mixin 之处就是在文章开头创建的两个组件内部。用下面的代码在两个组件中引入 clickMixin

```
import clickMixin from ‘../Mixins/clickMixin’
```

### Removing repeated logic
### 去除重复的逻辑

After importing the mixin, you have to remove the logic you had initially as it is now being taken care of by the mixin. In our case, this means that you will delete the method creation logic in the both components.
在引入了 mixin 后,你要移除即将被 mixin 替代的逻辑代码。在我们的例子中,这意味着你会在两个组件中删除方法的创建逻辑。

```
// remove this code block and the comma before it.
// 去掉这部分代码块以及它前面的逗号。

methods: {

Expand All @@ -220,9 +212,9 @@ methods: {
}
```

### Register the mixin
### 注册 mixin

This is where you tell the Vue application that what you imported is a mixin and so it should treat the logic inside it as one and do the dirty work of ensuring the application fixes the functionality and the method calls at the appropriate places in the component. Mixins in Vue by default are registered as arrays like it is below:
这步操作就是你告诉 Vue 应用你要导入 mixin,它会将其中的逻辑视为统一的并执行一些复杂的操作来保证应用的修复功能和方法在组件的适当位置调用。默认情况下,Vue 中的 Mixins 会以数组的形式被注册,如下所示:

```Vue
<script>
Expand All @@ -234,7 +226,7 @@ export default {
</script>
```

If you followed through from the start, your application components should be like it is below:
如果你从一开始就跟着我说的写,那么你的应用组件应该像下面这样:

**Test.vue**

Expand Down Expand Up @@ -316,31 +308,32 @@ display: inline-block;
font-size: 16px;
}
</style>
```

## Types of Mixins
```

There are two types of mixins in Vue:
## Mixins 的类型

1. **Local Mixins:** This is the type we have treated throughout this post. It is scoped to the component it is imported into and registered in. The powers of the local mixin is bound by the component it is imported in.
在 Vue 中 mixins 有两种类型:

2. **Global Mixins:** This is a different type of mixin that is defined in the Main.js file of any Vue project. It affects all Vue components in an application so the Vue team advises that it be used with caution. A definition of a global mixin looks like this:
1. **局部 Mixins:** 这就是我们在这篇文章中所处理的类型。它的范围仅局限于导入和注册的组件。局部 mixin 的影响范围由引入它的组件所决定。
2. **全局 Mixins:** 这是一种不同的 mixin,无论在任何 Vue 项目中,它是定义在 Main.js 文件中的。它会影响一个应用中的所有组件,所以 Vue 的开发团队建议要谨慎使用。一个全局 mixin 的定义看起来就像这样:

```JavaScript
Vue.mixin({
mounted() {
console.log("hello world!");
}
});

```

## Important things to note
## 特别注明

In the hierarchy of things in a Vue application, inside a component mixins are applied first by default. The component is applied second, so that it can override the mixin in any case. So it is important to always remember that when there is a kind of conflict of authority, the Vue component will always have the final say and overriding powers.
Vue 应用中的事务层结构中,组件内部应默认优先应用 mixins。组件的应用顺序次之,这样它可以在任意情况下重写覆盖 mixin。因此务必谨记,当出现某种权限冲突时,Vue 组件拥有有最终的解释和覆盖权。

## Conclusion
## 总结

You have been introduced to the concept of mixins in Vue, the types and how they are used with a sample demonstration. It is important you also remember to stick to local mixins and only use global mixins in rare cases when you really need it. Happy coding!
通过一个简单的示例,本文介绍了 Vue mixin 的概念、类型和使用方法。同样重要的是要坚持使用局部 mixins,并且只在一些极少的必须用到的情况下使用全局 mixins。编码愉快!

> 如果发现译文存在错误或其他需要改进的地方,欢迎到 [掘金翻译计划](https://github.com/xitu/gold-miner) 对译文进行修改并 PR,也可获得相应奖励积分。文章开头的 **本文永久链接** 即为本文在 GitHub 上的 MarkDown 链接。

Expand Down