diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 000000000..3a3fb0cf1
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,132 @@
+# cn.vuejs.org
+
+欢迎加入 [vuejs.org][vuejs.org] 中文翻译项目。
+
+访问中文网站:
+
+- http://cn.vuejs.org 放在 Github 上。
+- http://vuejs.org.cn 放在 Coding 上,在国内访问较快。
+
+参与:
+
+- 如果你看到错别字、漏译、错译,请直接提交 pr
+ ([帮助](https://help.github.com/articles/using-pull-requests/))。
+- 如果你看到网站问题,或者创建一个 issue,或者直接提交 pr。
+- 如果你对已有翻译有异议,建议创建一个 issue 讨论。
+- 如果你想修改英文内容,请去 [vuejs.org 项目][vuejs.org]。
+- 如果你想求教 Vue.js 使用问题,请去[论坛][forum]。
+- 如果你遇到 Vue.js 的问题,请去 [vue 项目][vue],
+ 创建 issue 并提供演示。可以在 JSBin, JSFiddle, Codepen 等网站创建演示。
+
+项目的分支:
+
+- `lang-zh` 翻译是在这个分支进行的,这是默认分支。
+- `master` 旧英文文档,不要改动。
+- `gh-pages` 网站发布在这个分支。
+
+相关网站与项目:
+
+- [vue.js 英文网站](http://vuejs.org)
+- [论坛][forum]
+- [vuejs.org 项目][vuejs.org]
+- [vue 项目][vue]
+
+## 翻译
+
+fork 这个项目,修改 `lang-zh` 分支下的文件,然后提交 pr。
+
+### 翻译要求
+
+- 汉字,字母,数字等之间以空格隔开。
+- 中文使用中文符号,英文使用英文符号。
+- 专有词注意大小写,如 HTML,CSS,JavaScript。
+- 术语与已有译文保持一致,如果有异议请先在 issue 中讨论。
+- 代码只翻译注释。
+- 标题会转化为链接,文档其它地方可能会用到,所以标题应尽量简短,
+ 在修改标题时搜索一下它是否还用在其它地方。
+ 同样的,在修改文档内链接时也应搜索一下。
+
+### 术语翻译对照
+
+- attribute 特性
+- transition 过渡
+
+### 不翻译的术语
+
+- getter, setter
+- prop
+
+## 同步英文网站
+
+下面的命令示例是直接操作这个项目,需要项目管理员权限。
+非项目管理员需要 fork 项目, 完成相关修改之后提交 pr。
+
+### 同步翻译
+
+初始化:
+
+```bash
+git pull git@github.com:vuejs/cn.vuejs.org.git
+cd cn.vuejs.org
+npm install
+npm install -g hexo-cli
+# 添加源 vuejs.org
+git remote add en git@github.com:vuejs/vuejs.org.git
+```
+
+每次更新:
+
+```bash
+# 拉取 cn.vuejs.org
+git pull
+# 拉取 vuejs.org
+git pull en master
+# 处理合并冲突
+git mergetool
+# 预览网站
+hexo serve
+# 推送更新
+git commit
+git push
+```
+
+使用 [Github 对比视图](https://github.com/vuejs/vuejs.org/compare)
+查看 [vuejs.org 项目][vuejs.org] 的变化,会看得清楚些。
+
+### 发布网站
+
+网站发布到 `gh-pages`分支,由项目下 `Makefile` 脚本自动完成。
+`Makefile` 先测试 vue 项目,故需要 clone [vue 项目][vue]。
+Windows 下运行这个脚本会有困难,建议在 Linux 或 Mac 下运行。
+
+目前 Vue.js 中文网站在国内用这个网址 http://vuejs.org.cn/ 访问会比较快,
+网站项目放在 [Coding](https://coding.net/u/limichange/p/cn.vuejs.org/) 上,
+由项目下的 `sync.sh` 脚本同步 Github。
+
+三个项目放到同一目录下,文件结构将是这样的:
+
+```
+├── cn.vuejs.org
+├── vue
+├── vuejs.org.cn
+```
+
+发布网站:
+
+```bash
+# 先更新 vue
+cd ../vue
+git pull origin master
+
+# 发布到 github
+cd ../cn.vuejs.org
+make
+
+# 同步到 coding
+cd ../vuejs.org.cn
+./sync.sh
+```
+
+[vuejs.org]: https://github.com/vuejs/vuejs.org
+[vue]: https://github.com/vuejs/vue
+[forum]: http://forum.vuejs.org
diff --git a/ISSUE_TEMPLATE.md b/ISSUE_TEMPLATE.md
new file mode 100644
index 000000000..9726f3403
--- /dev/null
+++ b/ISSUE_TEMPLATE.md
@@ -0,0 +1,9 @@
+如果不是翻译及网站问题,请勿创建 issue,谢谢。
+
+- 如果你是修改英文内容,请去 [vuejs.org 项目][vuejs.org]。
+- 如果你是求教 Vue.js 使用问题,请去[论坛][forum]。
+- 如果你是遇到 Vue.js 的问题,请去 [vue 项目][vue]。
+
+[vuejs.org]: https://github.com/vuejs/vuejs.org
+[vue]: https://github.com/vuejs/vue
+[forum]: http://forum.vuejs.org
diff --git a/README.md b/README.md
index 4ef988a0d..f99a675e2 100644
--- a/README.md
+++ b/README.md
@@ -1,10 +1,12 @@
-# vuejs.org
+# cn.vuejs.org
-This site is built with [hexo](http://hexo.io/). Site content is written in Markdown format located in `src`. Pull requests welcome!
+**[如何参与](CONTRIBUTING.md)?**
-## Developing
+这个网站使用 [hexo](http://hexo.io/) 创建。网站内容为 Markdown 格式,位于 `src` 目录下。
-Start a dev server at `localhost:4000`:
+## 开发
+
+启用开发服务器 `localhost:4000`:
```
$ npm install -g hexo-cli
diff --git a/_config.yml b/_config.yml
index 182ed390e..d07966646 100644
--- a/_config.yml
+++ b/_config.yml
@@ -97,7 +97,7 @@ markdown:
## Docs: http://zespia.tw/hexo/docs/deployment.html
deploy:
type: git
- repository: git@github.com:vuejs/vuejs.org.git
+ repository: git@github.com:vuejs/cn.vuejs.org.git
feed:
type: atom
diff --git a/src/CNAME b/src/CNAME
index 998cc417c..e1382460d 100644
--- a/src/CNAME
+++ b/src/CNAME
@@ -1 +1 @@
-vuejs.org
+cn.vuejs.org
diff --git a/src/_posts/announcing-2.0.md b/src/_posts/announcing-2.0.md
index 9071a1124..5dcdcdc37 100644
--- a/src/_posts/announcing-2.0.md
+++ b/src/_posts/announcing-2.0.md
@@ -3,8 +3,12 @@ title: Announcing Vue.js 2.0
date: 2016-04-27 13:33:00
---
+[中文翻译](http://jiongks.name/blog/announcing-vue-2/)
+
Today I am thrilled to announce the first public preview of Vue.js 2.0, which brings along many exciting improvements and new features. Let's take a peek at what's in store!
+
+
## Even Leaner, Even Faster
Vue.js has always focused on staying light and fast, but 2.0 pushes it even further. The rendering layer is now based on a lightweight virtual-DOM implementation that improves initial rendering speed and memory consumption by up to 2~4x in most scenarios (check out [these benchmarks](https://github.com/vuejs/vue/tree/next/benchmarks)). The template-to-virtual-DOM compiler and the runtime can be separated, so you can pre-compile templates and ship your app with only the runtime, which is less than 12kb min+gzip (as a reference, React 15 is 44kb min+gzip). The compiler also works in the browser, which means you can still drop in one script tag and start hacking, just like before. Even with the compiler included, the build is sitting at 17kb min+gzip, still lighter than the current 1.0 build.
diff --git a/src/api/index.md b/src/api/index.md
index 4a256cf17..db9a179e4 100644
--- a/src/api/index.md
+++ b/src/api/index.md
@@ -2,126 +2,127 @@
type: api
---
-## Global Config
+## 全局配置
-`Vue.config` is an object containing Vue's global configurations. You can modify its properties listed below before bootstrapping your application:
+`Vue.config` 是一个对象,包含 Vue 的全局配置。可以在启动应用之前修改下面属性:
### debug
-- **Type:** `Boolean`
+- **类型:** `Boolean`
-- **Default:** `false`
+- **默认值:** `false`
-- **Usage:**
+- **用法:**
``` js
Vue.config.debug = true
```
- When in debug mode, Vue will:
+ 在调试模式中,Vue 会:
- 1. Print stack traces for all warnings.
+ 1. 为所有的警告打印栈追踪。
- 2. Make all anchor nodes visible in the DOM as Comment nodes. This makes it easier to inspect the structure of the rendered result.
+ 2. 把所有的锚节点以注释节点显示在 DOM 中,更易于检查渲染结果的结构。
-
Debug mode is only available in development build.
+
+
只有开发版本可以使用调试模式。
### delimiters
-- **Type:** `Array`
+- **类型:** `Array`
-- **Default:** `{% raw %}["{{", "}}"]{% endraw %}`
+- **默认值:** `{% raw %}["{{", "}}"]{% endraw %}`
-- **Usage:**
+- **用法:**
``` js
- // ES6 template string style
+ // ES6 模板字符串
Vue.config.delimiters = ['${', '}']
```
- Change the plain text interpolation delimiters.
+ 修改文本插值的定界符。
### unsafeDelimiters
-- **Type:** `Array`
+- **类型:** `Array`
-- **Default:** `{% raw %}["{{{", "}}}"]{% endraw %}`
+- **默认值:** `{% raw %}["{{{", "}}}"]{% endraw %}`
-- **Usage:**
+- **用法:**
``` js
// make it look more dangerous
Vue.config.unsafeDelimiters = ['{!!', '!!}']
```
- Change the raw HTML interpolation delimiters.
+ 修改原生 HTML 插值的定界符。
### silent
-- **Type:** `Boolean`
+- **类型:** `Boolean`
-- **Default:** `false`
+- **默认值:** `false`
-- **Usage:**
+- **用法:**
``` js
Vue.config.silent = true
```
- Suppress all Vue.js logs and warnings.
+ 取消 Vue.js 所有的日志与警告。
### async
-- **Type:** `Boolean`
+- **类型:** `Boolean`
-- **Default:** `true`
+- **默认值:** `true`
-- **Usage:**
+- **用法:**
``` js
Vue.config.async = false
```
- When async mode is off, Vue will perform all DOM updates synchronously upon detecting data change. This may help with debugging in some scenarios, but could also cause degraded performance and affect the order in which watcher callbacks are called. **`async: false` is not recommended in production.**
+ 如果关闭了异步模式,Vue 在检测到数据变化时同步更新 DOM。在有些情况下这有助于调试,但是也可能导致性能下降,并且影响 watcher 回调的调用顺序。**`async: false`不推荐用在生产环境中。**
### devtools
-- **Type:** `Boolean`
+- **类型:** `Boolean`
-- **Default:** `true` (`false` in production builds)
+- **默认值:** `true` (生产版为 `false`)
-- **Usage:**
+- **用法:**
``` js
- // make sure to set this synchronously immediately after loading Vue
+ // 在加载 Vue 之后立即同步的设置
Vue.config.devtools = true
```
- Configure whether to allow [vue-devtools](https://github.com/vuejs/vue-devtools) inspection. This option's default value is `true` in development builds and `false` in production builds. You can set it to `true` to enable inspection for production builds.
+ 配置是否允许 [vue-devtools](https://github.com/vuejs/vue-devtools) 检查代码。开发版默认为 `true`, 生产版默认为 `false`。 生产版设为 `true` 可以启用检查。
-## Global API
+## 全局 API
Vue.extend( options )
-- **Arguments:**
+- **参数:**
- `{Object} options`
-- **Usage:**
+- **用法:**
- Create a "subclass" of the base Vue constructor. The argument should be an object containing component options.
+ 创建基础 Vue 构造器的“子类”。参数是一个对象,包含组件选项。
- The special cases to note here are `el` and `data` options - they must be functions when used with `Vue.extend()`.
+ 这里要注意的特例是 `el` 和 `data` 选项—— 在 `Vue.extend()` 中它们必须是函数。
``` html
```
``` js
- // create reusable constructor
+ // 创建可复用的构造器
var Profile = Vue.extend({
template: '
{{firstName}} {{lastName}} aka {{alias}}
'
})
- // create an instance of Profile
+ // 创建一个 Profile 实例
var profile = new Profile({
data: {
firstName: 'Walter',
@@ -129,268 +130,269 @@ type: api
alias: 'Heisenberg'
}
})
- // mount it on an element
+ // 挂载到元素上
profile.$mount('#mount-point')
```
- Will result in:
+ 结果:
``` html
-- **Arguments:**
+- **参数:**
- `{Function} callback`
-- **Usage:**
+- **用法:**
- Defer the callback to be executed after the next DOM update cycle. Use it immediately after you've changed some data to wait for the DOM update.
+ 延迟回调在下次 DOM 更新循环之后执行。在修改数据之后立即使用这个方法,等待 DOM 更新。
``` js
- // modify data
+ // 修改数据
vm.msg = 'Hello'
- // DOM not updated yet
+ // DOM 没有更新
Vue.nextTick(function () {
- // DOM updated
+ // DOM 更新了
})
```
-- **See also:** [Async Update Queue](/guide/reactivity.html#Async-Update-Queue)
+- **另见:** [异步更新队列](/guide/reactivity.html#异步更新队列)
Vue.set( object, key, value )
-- **Arguments:**
+- **参数:**
- `{Object} object`
- `{String} key`
- `{*} value`
-- **Returns:** the set value.
+- **返回值:** 设置的值
-- **Usage:**
+- **用法:**
- Set a property on an object. If the object is reactive, ensure the property is created as a reactive property and trigger view updates. This is primarily used to get around the limitation that Vue cannot detect property additions.
+ 设置对象的属性。如果对象是响应的,将触发视图更新。这个方法主要用于解决 不能检测到属性添加的限制。
-- **See also:** [Reactivity in Depth](/guide/reactivity.html)
+- **另见:** [深入响应式原理](/guide/reactivity.html)
Vue.delete( object, key )
-- **Arguments:**
+- **参数:**
- `{Object} object`
- `{String} key`
-- **Usage:**
+- **用法:**
- Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.
+ 删除对象的属性。如果对象是响应的,将触发视图更新。这个方法主要用于解决 不能检测到属性删除的限制。
-- **See also:** [Reactivity in Depth](/guide/reactivity.html)
+- **另见:** [深入响应式原理](/guide/reactivity.html)
Vue.directive( id, [definition] )
-- **Arguments:**
+- **参数:**
- `{String} id`
- `{Function | Object} [definition]`
-- **Usage:**
+- **用法:**
- Register or retrieve a global directive.
+ 注册或获取全局指令。
``` js
- // register
+ // 注册
Vue.directive('my-directive', {
bind: function () {},
update: function () {},
unbind: function () {}
})
- // register (simple function directive)
+ // 注册,传入一个函数
Vue.directive('my-directive', function () {
// this will be called as `update`
})
- // getter, return the directive definition if registered
+ // getter,返回已注册的指令
var myDirective = Vue.directive('my-directive')
```
-- **See also:** [Custom Directives](/guide/custom-directive.html)
+- **另见:** [自定义指令](/guide/custom-directive.html)
Vue.elementDirective( id, [definition] )
-- **Arguments:**
+- **参数:**
- `{String} id`
- `{Object} [definition]`
-- **Usage:**
+- **用法:**
- Register or retrieve a global element directive.
+ 注册或获取全局的元素指令。
``` js
- // register
+ // 注册
Vue.elementDirective('my-element', {
bind: function () {},
- // element directives do not use `update`
+ // 没有使用 `update`
unbind: function () {}
})
- // getter, return the directive definition if registered
+ // getter,返回已注册的元素指令
var myDirective = Vue.elementDirective('my-element')
```
-- **See also:** [Element Directives](/guide/custom-directive.html#Element-Directives)
+- **另见:** [元素指令](/guide/custom-directive.html#元素指令)
Vue.filter( id, [definition] )
-- **Arguments:**
+- **参数:**
- `{String} id`
- `{Function | Object} [definition]`
-- **Usage:**
+- **用法:**
- Register or retrieve a global filter.
+ 注册或获取全局过滤器。
``` js
- // register
+ // 注册
Vue.filter('my-filter', function (value) {
- // return processed value
+ // 返回处理后的值
})
- // two way filter
+ // 双向过滤器
Vue.filter('my-filter', {
read: function () {},
write: function () {}
})
- // getter, return the filter if registered
+ // getter,返回已注册的指令
var myFilter = Vue.filter('my-filter')
```
-- **See also:** [Custom Filter](/guide/custom-filter.html)
+- **另见:** [自定义过滤器](/guide/custom-filter.html)
-- **Arguments:**
+- **参数:**
- `{Object | Function} plugin`
- `{Object} [options]`
-- **Usage:**
+- **用法:**
- Install a Vue.js plugin. If the plugin is an Object, it must expose an `install` method. If it is a function itself, it will be treated as the install method. The install method will be called with Vue as the argument.
+ 安装 Vue.js 插件。如果插件是一个对象,必须有一个 `install` 方法。如果它是一个函数,它会被作为安装方法。安装方法以 Vue 为参数。
-- **See also:** [Plugins](/guide/plugins.html).
+- **另见:** [插件](/guide/plugins.html)
Vue.mixin( mixin )
-- **Arguments:**
+- **参数:**
- `{Object} mixin`
-- **Usage:**
+- **用法:**
- Apply a mixin globally, which affects every Vue instance created afterwards. This can be used by plugin authors to inject custom behavior into components. **Not recommended in application code**.
+ 全局应用一个混合,将影响所有 Vue 实例。插件作者可以用它向组件注入自定义逻辑。**不推荐用在应用代码中。**
-- **See also:** [Global Mixins](/guide/mixins.html#Global-Mixin)
+- **另见:** [全局混合](/guide/mixins.html#全局混合)
-## Options / Data
+## 选项 / 数据
### data
-- **Type:** `Object | Function`
+- **类型:** `Object | Function`
+
+- **限制:** 在组件定义中只能是函数。
-- **Restriction:** Only accepts `Function` when used in a component definition.
+- **详细:**
-- **Details:**
+ Vue 实例的数据对象。Vue.js 会递归地将它全部属性转为 getter/setter,从而让它能响应数据变化。**这个对象必须是普通对象**:原生对象,getter/setter 及原型属性会被忽略。不推荐观察复杂对象。
- The data object for the Vue instance. Vue.js will recursively convert its properties into getter/setters to make it "reactive". **The object must be plain**: native objects, existing getter/setters and prototype properties are ignored. It is not recommended to observe complex objects.
+ 在实例创建之后,可以用 `vm.$data` 访问原始数据对象。Vue 实例也代理了数据对象所有的属性。
- Once the instance is created, the original data object can be accessed as `vm.$data`. The Vue instance also proxies all the properties found on the data object.
+ 在定义**组件**时,同一定义将创建多个实例,此时 `data` 必须是一个函数,返回原始数据对象。如果 `data` 仍然是一个普通对象,则所有的实例将指向同一个对象!换成函数后,每当创建一个实例时,会调用这个函数,返回一个新的原始数据对象的副本。
- Properties that start with `_` or `$` will **not** be proxied on the Vue instance because they may conflict with Vue's internal properties and API methods. You will have to access them as `vm.$data._property`.
+ 名字以 `_` 或 `$`开始的属性**不会**被 Vue 实例代理,因为它们可能与 Vue 的内置属性与 API 方法冲突。用 `vm.$data._property` 访问它们。
- When defining a **component**, `data` must be declared as a function that returns the initial data object, because there will be many instances created using the same definition. If we still use a plain object for `data`, that same object will be **shared by reference** across all instance created! By providing a `data` function, every time a new instance is created, we can simply call it to return a fresh copy of the initial data.
+ 可以通过将 `vm.$data` 传入 `JSON.parse(JSON.stringify(...))` 得到原始数据对象。
- If required, a deep clone of the original object can be obtained by passing `vm.$data` through `JSON.parse(JSON.stringify(...))`.
-- **Example:**
+- **示例:**
``` js
var data = { a: 1 }
- // direct instance creation
+ // 直接创建一个实例
var vm = new Vue({
data: data
})
vm.a // -> 1
vm.$data === data // -> true
- // must use function when in Vue.extend()
+ // 在 Vue.extend() 中必须是函数
var Component = Vue.extend({
data: function () {
return { a: 1 }
@@ -398,55 +400,55 @@ type: api
})
```
-- **See also:** [Reactivity in Depth](/guide/reactivity.html).
+- **另见:** [深入响应式原理](/guide/reactivity.html)
### props
-- **Type:** `Array | Object`
+- **类型:** `Array | Object`
-- **Details:**
+- **详细:**
- A list/hash of attributes that are exposed to accept data from the parent component. It has a simple Array-based syntax and an alternative Object-based syntax that allows advanced configurations such as type checking, custom validation and default values.
+ 包含一些特性——期望使用的父组件数据的属性。可以是数组或对象。对象用于高级配置,如类型检查,自定义验证,默认值等。
-- **Example:**
+- **示例:**
``` js
- // simple syntax
+ // 简单语法
Vue.component('props-demo-simple', {
props: ['size', 'myMessage']
})
- // object syntax with validation
+ // 对象语法,指定验证要求
Vue.component('props-demo-advanced', {
props: {
- // just type check
+ // 只检测类型
size: Number,
- // type check plus other validations
+ // 检测类型 + 其它验证
name: {
type: String,
required: true,
- // warn if not two way bound
+ // 双向绑定
twoWay: true
}
}
})
```
-- **See also:** [Props](/guide/components.html#Props)
+- **另见:** [Props](/guide/components.html#Props)
### propsData
> 1.0.22+
-- **Type:** `Object`
+- **类型:** `Object`
-- **Restriction:** only respected in instance creation via `new`.
+- **限制:** 只用于 `new` 创建实例中。
-- **Details:**
+- **详细:**
- Pass props to an instance during its creation. This is primarily intended to make unit testing easier.
+ 在创建实例的过程传递 props。主要作用是方便测试。
-- **Example:**
+- **示例:**
``` js
var Comp = Vue.extend({
@@ -463,23 +465,23 @@ type: api
### computed
-- **Type:** `Object`
+- **类型:** `Object`
-- **Details:**
+- **详细:**
- Computed properties to be mixed into the Vue instance. All getters and setters have their `this` context automatically bound to the Vue instance.
+ 实例计算属性。getter 和 setter 的 `this` 自动地绑定到实例。
-- **Example:**
+- **示例:**
```js
var vm = new Vue({
data: { a: 1 },
computed: {
- // get only, just need a function
+ // 仅读取,值只须为函数
aDouble: function () {
return this.a * 2
},
- // both get and set
+ // 读取和设置
aPlus: {
get: function () {
return this.a + 1
@@ -496,19 +498,19 @@ type: api
vm.aDouble // -> 4
```
-- **See also:**
- - [Computed Properties](/guide/computed.html)
- - [Reactivity in Depth: Inside Computed Properties](/guide/reactivity.html#Inside-Computed-Properties)
+- **另见:**
+ - [计算属性](/guide/computed.html)
+ - [深入响应式原理:计算属性的奥秘](/guide/reactivity.html#计算属性的奥秘)
### methods
-- **Type:** `Object`
+- **类型:** `Object`
-- **Details:**
+- **详细:**
- Methods to be mixed into the Vue instance. You can access these methods directly on the VM instance, or use them in directive expressions. All methods will have their `this` context automatically bound to the Vue instance.
+ 实例方法。实例可以直接访问这些方法,也可以用在指令表达式内。方法的 `this` 自动绑定到实例。
-- **Example:**
+- **示例:**
```js
var vm = new Vue({
@@ -523,17 +525,17 @@ type: api
vm.a // 2
```
-- **See also:** [Methods and Event Handling](/guide/events.html)
+- **另见:** [方法与事件处理器](/guide/events.html)
### watch
-- **Type:** `Object`
+- **类型:** `Object`
-- **Details:**
+- **详细:**
- An object where keys are expressions to watch and values are the corresponding callbacks. The value can also be a string of a method name, or an Object that contains additional options. The Vue instance will call `$watch()` for each entry in the object at instantiation.
+ 一个对象,键是观察表达式,值是对应回调。值也可以是方法名,或者是对象,包含选项。在实例化时为每个键调用 `$watch()` 。
-- **Example:**
+- **示例:**
``` js
var vm = new Vue({
@@ -544,9 +546,9 @@ type: api
'a': function (val, oldVal) {
console.log('new: %s, old: %s', val, oldVal)
},
- // string method name
+ // 方法名
'b': 'someMethod',
- // deep watcher
+ // 深度 watcher
'c': {
handler: function (val, oldVal) { /* ... */ },
deep: true
@@ -556,56 +558,56 @@ type: api
vm.a = 2 // -> new: 2, old: 1
```
-- **See also:** [Instance Methods - vm.$watch](#vm-watch)
+- **另见:** [实例方法 - vm.$watch](#vm-watch)
-## Options / DOM
+## 选项 / DOM
### el
-- **Type:** `String | HTMLElement | Function`
+- **类型:** `String | HTMLElement | Function`
-- **Restriction:** only accepts type `Function` when used in a component definition.
+- **限制:** 在组件定义中只能是函数。
-- **Details:**
+- **详细:**
- Provide the Vue instance an existing DOM element to mount on. It can be a CSS selector string, an actual HTMLElement, or a function that returns an HTMLElement. Note that the provided element merely serves as a mounting point; it will be replaced if a template is also provided, unless `replace` is set to false. The resolved element will be accessible as `vm.$el`.
+ 为实例提供挂载元素。值可以是 CSS 选择符,或实际 HTML 元素,或返回 HTML 元素的函数。注意元素只用作挂载点。如果提供了模板则元素被替换,除非 `replace` 为 false。元素可以用 `vm.$el` 访问。
- When used in `Vue.extend`, a function must be provided so each instance gets a separately created element.
+ 用在 `Vue.extend` 中必须是函数值,这样所有实例不会共享元素。
- If this option is available at instantiation, the instance will immediately enter compilation; otherwise, the user will have to explicitly call `vm.$mount()` to manually start the compilation.
+ 如果在初始化时指定了这个选项,实例将立即进入编译过程。否则,需要调用 `vm.$mount()`,手动开始编译。
-- **See also:** [Lifecycle Diagram](/guide/instance.html#Lifecycle-Diagram)
+- **另见:** [生命周期图示](/guide/instance.html#生命周期图示)
### template
-- **Type:** `String`
+- **类型:** `String`
-- **Details:**
+- **详细:**
- A string template to be used as the markup for the Vue instance. By default, the template will **replace** the mounted element. When the `replace` option is set to `false`, the template will be inserted into the mounted element instead. In both cases, any existing markup inside the mounted element will be ignored, unless content distribution slots are present in the template.
+ 实例模板。模板默认**替换**挂载元素。如果 `replace` 选项为 `false`,模板将插入挂载元素内。两种情况下,挂载元素的内容都将被忽略,除非模板有内容分发 slot。
- If the string starts with `#` it will be used as a querySelector and use the selected element's innerHTML as the template string. This allows the use of the common `
{% endraw %}
-- **Additional Examples:**
+- **另一个示例:**
- Multiple search keys:
+ 多搜索字段:
``` html
```
- Multiple search keys with a dynamic Array argument:
+ 多搜索字段为一个动态数组:
``` html
```
- Use a custom filter function:
+ 使用自定义过滤函数:
``` html
@@ -2161,21 +2158,21 @@ type: api
### orderBy
-- **Limited to:** directives that expect `Array` values, e.g. `v-for`
+- **限制:** 指令的值须是数组,如 `v-for`
-- **Arguments:**
+- **参数:**
- `{String | Array | Function} ...sortKeys`
- - `{String} [order] - default: 1`
+ - `{String} [order] - 默认值:1`
-- **Usage:**
+- **用法:**
- Return a sorted version of the source Array. You can pass any number of Strings to sort on keys. You can also pass an array containing the sorting keys or a Function if you want to use your own sorting strategy instead. The optional `order` argument specifies whether the result should be in ascending (`order >= 0`) or descending (`order < 0`) order.
+ 返回排序后的数组。你可以传入多个键名。你也可以传入一个数组,此数组包含排序的键名。如果你想使用自己的排序策略,可以传入一个函数。可选参数 `order` 决定结果升序(`order >= 0`)或降序(`order < 0`)。
- For arrays of primitive values, simply omit `sortKeys` and provide the order, e.g. `orderBy 1`.
+ 对于原始类型数组,可以忽略 `sortKey` ,只提供排序,例如 `orderBy 1`。
-- **Example:**
+- **示例:**
- Sort users by name:
+ 按名字排序用户:
``` html
@@ -2185,7 +2182,7 @@ type: api
```
- In descending order:
+ 降序:
``` html
@@ -2195,7 +2192,7 @@ type: api
```
- Sort primitive values:
+ 原始类型数组:
``` html
@@ -2205,7 +2202,7 @@ type: api
```
- Dynamic sort order:
+ 动态排序:
``` html
@@ -2228,7 +2225,7 @@ type: api
})
```
- Sort using two keys:
+ 使用两个键名排序:
``` html
@@ -2258,7 +2255,7 @@ type: api
{% endraw %}
- Sort using a Function:
+ 使用一个函数排序:
``` html
@@ -2337,38 +2334,38 @@ type: api
{% endraw %}
-## Array Extension Methods
+## 数组扩展方法
-Vue.js extends `Array.prototype` with two additional methods that makes it easier to perform some common Array operations while ensuring reactive updates are properly triggered.
+Vue.js 在 `Array.prototype` 上添加了两个方法,以方便常见的数组操作,并且能触发视图更新。
### array.$set(index, value)
-- **Arguments**
+- **参数:**
- `{Number} index`
- `{*} value`
-- **Usage**
+- **用法:**
- Set an element in the array to a value by index and trigger view updates.
+ 通过索引设置数组元素并触发视图更新。
``` js
vm.animals.$set(0, { name: 'Aardvark' })
```
-- **See also:** [Array Detection Caveats](/guide/list.html#Caveats)
+- **另见:** [数组检测问题](/guide/list.html#问题)
### array.$remove(reference)
-- **Arguments**
+- **参数:**
- `{Reference} reference`
-- **Usage**
+- **用法:**
- Remove an element from an array by reference and trigger view updates. This is a sugar method for first searching for the element in the array, and then if found, calling `array.splice(index, 1)`.
+ 通过索引删除数组元素并触发视图更新。这个方法先在数组中搜索这个元素,如果找到了则调用 `array.splice(index, 1)`。
``` js
var aardvark = vm.animals[0]
vm.animals.$remove(aardvark)
```
-- **See also:** [Mutation Methods](/guide/list.html#Mutation-Methods)
+- **另见:** [变异方法](/guide/list.html#变异方法)
diff --git a/src/examples/commits.md b/src/examples/commits.md
index 2e6075280..bc6514747 100644
--- a/src/examples/commits.md
+++ b/src/examples/commits.md
@@ -1,9 +1,9 @@
---
-title: GitHub Commits
+title: GitHub 提交
type: examples
order: 1
---
-> This example fetches latest Vue.js commits data from GitHub's API and displays them as a list. You can switch between the master and dev branches.
+> 这个例子通过 GitHub 的 API 获取 Vue.js 最近的提交记录,并展示为一个列表。你可以在 master 和 dev 分支之间切换。
diff --git a/src/examples/firebase.md b/src/examples/firebase.md
index ebfcb32a3..bce87f846 100644
--- a/src/examples/firebase.md
+++ b/src/examples/firebase.md
@@ -1,9 +1,9 @@
---
-title: Firebase + Validation
+title: Firebase + 验证
type: examples
order: 2
---
-> This example uses [Firebase](https://www.firebase.com/) as the data persistence backend and syncs between clients in real time (you can try opening it in multiple browser tabs). In addition, it performs instant validation using computed properties and triggers CSS transitions when adding/removing items.
+> 这个例子使用 [Firebase](https://www.firebase.com/) 作为后台数据存储,并与客户端实时同步 (你可以在多个浏览器标签中打开它)。另外,它使用计算属性实时校验,并且在添加/删除项目时触发 CSS 过渡效果。
diff --git a/src/examples/grid-component.md b/src/examples/grid-component.md
index b5bad5cc6..c8ddebea8 100644
--- a/src/examples/grid-component.md
+++ b/src/examples/grid-component.md
@@ -1,9 +1,9 @@
---
-title: Grid Component
+title: 表格组件
type: examples
order: 3
---
-> This is an example of creating a reusable grid component and using it with external data.
+> 这个例子创建了一个可复用的表格组件,用外部数据使用它。
diff --git a/src/examples/hackernews.md b/src/examples/hackernews.md
index fcb5f3cd5..6565420ef 100644
--- a/src/examples/hackernews.md
+++ b/src/examples/hackernews.md
@@ -1,10 +1,10 @@
---
-title: HackerNews Clone
+title: HackerNews 克隆
type: examples
order: 10
---
-> This is a HackerNews clone built upon HN's official Firebase API, and using Webpack + vue-loader for the build setup.
+> 这是 HackerNews 的克隆,建立在 HN 官方的 Firebase API 上,并且使用 Webpack + vue-loader 构建。
diff --git a/src/examples/index.md b/src/examples/index.md
index f4c072278..08477af5c 100644
--- a/src/examples/index.md
+++ b/src/examples/index.md
@@ -1,9 +1,9 @@
---
-title: Markdown Editor
+title: Markdown 编辑器
type: examples
order: 0
---
-> Dead simple Markdown editor.
+> 极简的 Markdown 编辑器。
diff --git a/src/examples/modal.md b/src/examples/modal.md
index 61e491a86..dd48a7745 100644
--- a/src/examples/modal.md
+++ b/src/examples/modal.md
@@ -1,9 +1,9 @@
---
-title: Modal Component
+title: 模态组件
type: examples
order: 6
---
-> Features used: component, prop passing, content insertion, transitions.
+> 用到的特性:组件、prop 传递、内容传入、过渡。
diff --git a/src/examples/select2.md b/src/examples/select2.md
index 012bd5df6..239f7c7e7 100644
--- a/src/examples/select2.md
+++ b/src/examples/select2.md
@@ -1,9 +1,9 @@
---
-title: Custom Directive
+title: 自定义指令
type: examples
order: 8
---
-> In this example we are integrating a 3rd party jQuery plugin (select2) by wrapping it inside a custom directive.
+> 在这个例子中,Vue.js 与一个第三方 jQuery 插件(select2) 整合,通过将它包装到一个自定义指令中实现。
diff --git a/src/examples/svg.md b/src/examples/svg.md
index 9675cd5c2..b1d6039fe 100644
--- a/src/examples/svg.md
+++ b/src/examples/svg.md
@@ -1,9 +1,9 @@
---
-title: SVG Graph
+title: SVG 图形
type: examples
order: 5
---
-> This example showcases a combination of custom component, computed property, two-way binding and SVG support.
+> 这个例子演示了综合使用自定义组件、计算属性、双向绑定及 SVG 支持。
diff --git a/src/examples/todomvc.md b/src/examples/todomvc.md
index 65839bef2..aaf96c61c 100644
--- a/src/examples/todomvc.md
+++ b/src/examples/todomvc.md
@@ -4,7 +4,7 @@ type: examples
order: 9
---
-> This is a fully spec-compliant TodoMVC implementation in under 120 effective lines of JavaScript (excluding comments and blank lines).
+> 这是一个完全符合规范的 TodoMVC 实现,JavaScript 代码不超过 120 行 (除去注释和空行)。
diff --git a/src/examples/tree-view.md b/src/examples/tree-view.md
index c57287187..e1823369f 100644
--- a/src/examples/tree-view.md
+++ b/src/examples/tree-view.md
@@ -1,9 +1,9 @@
---
-title: Tree View
+title: 树状视图
type: examples
order: 4
---
-> Example of a simple tree view implementation showcasing recursive usage of components.
+> 这个例子实现了一个简单的树状视图,演示如何递归使用组件。
diff --git a/src/guide/application.md b/src/guide/application.md
index 379820be8..8628ccf9b 100644
--- a/src/guide/application.md
+++ b/src/guide/application.md
@@ -1,49 +1,49 @@
---
-title: Building Large-Scale Apps
+title: 构建大型应用
type: guide
order: 18
---
-> **NEW:** Get up and running with single file Vue components, hot-reload, lint-on-save and unit testing in minutes with [vue-cli](https://github.com/vuejs/vue-cli)!
+> **新:** 使用脚手架工具 [vue-cli](https://github.com/vuejs/vue-cli) 可以快速地构建项目:单文件 Vue 组件,热加载,保存时检查代码,单元测试等。
-The Vue.js core library is designed to be focused and flexible - it's just a view layer library that doesn't enforce any application-level architecture. While this can be great for integrating with existing projects, it could be a challenge for those with less experience to build larger scale applications from scratch.
+Vue.js 的设计思想是专注与灵活——它只是一个界面库,不强制使用哪个架构。它能很好地与已有项目整合,不过对于经验欠缺的开发者,从头开始构建大型应用可能是一个挑战。
-The Vue.js ecosystem provides a set of tools and libraries on how to build large SPAs with Vue. This part is where we start get a bit "framework"-ish, but it's really just an opinionated list of recommendations; you still get to pick what to use for each part of the stack.
+Vue.js 生态系统提供了一系列的工具与库,用于构建大型单页应用。这些部分会感觉开始更像一个『框架』,但是它们本质上只是一套推荐的技术栈而已 - 你依然可以对各个部分进行选择和替换。
-## Modularization
+## 模块化
-For large projects it's necessary to utilize a modularized build system to better organize your code. The recommended approach of doing so is by writing your source code in CommonJS or ES6 modules and bundle them using [Webpack](http://webpack.github.io/) or [Browserify](http://browserify.org/).
+对于大型项目,为了更好地管理代码使用模块构建系统非常必要。推荐代码使用 CommonJS 或 ES6 模块,然后使用 [Webpack](http://webpack.github.io/) 或 [Browserify](http://browserify.org/) 打包。
-Webpack and Browserify are more than just module bundlers, though. They both provide source transform APIs that allow you to transform your source code with other pre-processors. For example, you can write your code with future ES2015/2016 syntax using [babel-loader](https://github.com/babel/babel-loader) or [babelify](https://github.com/babel/babelify).
+Webpack 和 Browserify 不只是模块打包器。两者都提供了源码转换 API,通过它可以用其它预处理器转换源码。例如,借助 [babel-loader](https://github.com/babel/babel-loader) 或 [babelify](https://github.com/babel/babelify) 代码可以使用 ES2015/2016 语法。
-If you've never used them before, I highly recommend going through a few tutorials to get familiar with the concept of module bundlers, and start writing JavaScript using the latest ECMAScript features.
+如果你之前没有用过它们,我强烈推荐你阅读一些教程,了解模块打包器,然后使用最新的 ECMAScript 特性写 JavaScript。
-## Single File Components
+## 单文件组件
-In a typical Vue.js project we will be dividing our interface into many small components, and it would be nice to have each component encapsulate its CSS styles, template and JavaScript definition in the same place. As mentioned above, when using Webpack or Browserify, with proper source transforms we can write our components like this:
+在典型的 Vue.js 项目中,我们会把界面拆分为多个小组件,每个组件在同一地方封装它的 CSS 样式,模板和 JavaScript 定义,这么做比较好。如上所述,使用 Webpack 或 Browserify 以及合适的源码转换器,我们可以这样写组件:
-If you are into pre-processors, you can even do this:
+如果你喜欢预处理器,甚至可以这么做:
-You can build these single-file Vue components with Webpack + [vue-loader](https://github.com/vuejs/vue-loader) or Browserify + [vueify](https://github.com/vuejs/vueify). You can also play with it online at [Webpackbin.com](http://www.webpackbin.com/vue)!
+你可以使用 Webpack + [vue-loader](https://github.com/vuejs/vue-loader) 或 Browserify + [vueify](https://github.com/vuejs/vueify) 构建这些单文件 Vue 组件。你也可以在 [Webpackbin.com](http://www.webpackbin.com/vue) 上在线尝试!
-Which build tool to choose is largely dependent on your experience and needs. Webpack-based setup offers more powerful features such as code splitting, processing static assets as module dependencies and extracting component CSS into a separate file, but can be a bit more complex to configure. Browserify can be easier to setup in scenarios where you don't need the advanced features that Webpack offers.
+选择哪种构建工具取决于你的经验和需求。Webpack 的功能更强大,如代码分割,将静态资源当作模块,提取组件的 CSS 到单独的一个文件等,不过它的配置相对复杂一点。如果你不需要 Webpack 的那些功能,使用 Browserify 更简单,
-The fastest way to get up and running with a pre-configured build setup is using the official [vue-cli](https://github.com/vuejs/vue-cli). You can also find the official scaffold templates on GitHub:
+最快的构建方式是使用官方出品的脚手架工具 [vue-cli](https://github.com/vuejs/vue-cli)。你也可以在 GitHub 上查看官方的构建模板:
- [Webpack + vue-loader](https://github.com/vuejs-templates/webpack)
- [Browserify + vueify](https://github.com/vuejs-templates/browserify)
-## Routing
+## 路由
-For Single Page Applications, it is recommended to use the [official vue-router library](https://github.com/vuejs/vue-router), which is currently in technical preview. For more details, please refer to vue-router's [documentation](http://vuejs.github.io/vue-router/).
+对于单页应用,推荐使用[官方库 vue-router](https://github.com/vuejs/vue-router)。详细请查看它的[文档](http://vuejs.github.io/vue-router/)。
-If you just need some very simple routing logic, you can also implement it by manually listening on `hashchange` and utilizing a dynamic component:
+如果你只需要非常简单的路由逻辑,可以这么做,监听 `hashchange` 事件并使用动态组件:
-**Example:**
+**示例:**
``` html
@@ -60,19 +60,19 @@ var app = new Vue({
currentView: 'home'
}
})
-// Switching pages in your route handler:
+// 在路由处理器中切换页面
app.currentView = 'page1'
```
-With this mechanism it's also very easy to leverage external routing libraries such as [Page.js](https://github.com/visionmedia/page.js) or [Director](https://github.com/flatiron/director).
+利用这种机制也可以非常容易地配合其它路由库,如 [Page.js](https://github.com/visionmedia/page.js) 或 [Director](https://github.com/flatiron/director)。
-## Communication with Server
+## 与服务器通信
-All Vue instances can have their raw `$data` directly serialized with `JSON.stringify()` with no additional effort. The community has contributed the [vue-resource](https://github.com/vuejs/vue-resource) plugin, which provides an easy way to work with RESTful APIs. You can also use any Ajax library you like, e.g. `$.ajax` or [SuperAgent](https://github.com/visionmedia/superagent). Vue.js also plays nicely with no-backend services such as Firebase and Parse.
+Vue 实例的原始数据 `$data` 能直接用 `JSON.stringify()` 序列化。社区贡献了一个插件 [vue-resource](https://github.com/vuejs/vue-resource),提供一种容易的方式与 RESTful APIs 配合。也可以使用任何自己喜欢的 Ajax 库,如 `$.ajax` 或 [SuperAgent](https://github.com/visionmedia/superagent)。Vue.js 也能很好地与无后端服务配合,如 Firebase 和 Parse。
-## State Management
+## 状态管理
-In large applications, state management often becomes complex due to multiple pieces of state scattered across many components and the interactions between them. It is often overlooked that the source of truth in Vue.js applications is the raw data object - a Vue instance simply proxies access to it. Therefore, if you have a piece of state that should be shared by multiple instances, you should avoid duplicating it. Instead, share it by identity:
+在大型应用中,状态管理常常变得复杂,因为状态分散在许多组件内。常常忽略 Vue.js 应用的来源是原生的数据对象—— Vue 实例代理访问它。因此,如果一个状态要被多个实例共享,应避免复制它:
``` js
var sourceOfTruth = {}
@@ -86,7 +86,7 @@ var vmB = new Vue({
})
```
-Now whenever `sourceOfTruth` is mutated, both `vmA` and `vmB` will update their views automatically. Extending this idea further, we would arrive at the **store pattern**:
+现在每当 `sourceOfTruth` 被修改后,`vmA` 与 `vmB` 将自动更新它们的视图。扩展这个思路,我们可以实现 **store 模式**:
``` js
var store = {
@@ -116,21 +116,21 @@ var vmB = new Vue({
})
```
-Notice we are putting all actions that mutate the store's state inside the store itself. This type of centralized state management makes it easier to understand what type of mutations could happen to the state, and how are they triggered. Each component can still own and manage its private state.
+我们把所有的 action 放在 store 内,action 修改 store 的状态。集中管理状态更易于理解状态将怎样变化。组件仍然可以拥有和管理它的私有状态。
-
+
-One thing to take note is that you should never replace the original state object in your actions - the components and the store need to share reference to the same object in order for the mutations to be observed.
+有一点要注意,不要在 action 中替换原始的状态对象——为了观察到变化,组件和 store 需要共享这个对象。
-If we enforce a convention where components are never allowed to directly mutate state that belongs to a store, but should instead dispatch events that notify the store to perform actions, we've essentially arrived at the [Flux](https://facebook.github.io/flux/) architecture. The benefit of this convention is we can record all state mutations happening to the store, and on top of that we can implement advanced debugging helpers such as mutation logs, snapshots, history re-rolls, etc.
+如果我们约定,组件不可以直接修改 store 的状态,而应当派发事件,通知 store 执行 action,那么我们基本上实现了 [Flux](https://facebook.github.io/flux/) 架构。此约定的好处是,我们能记录 store 所有的状态变化,并且在此之上实现高级的调试帮助函数,如修改日志,快照,历史回滚等。
-The Flux architecture is commonly used in React applications, but it can be applied to Vue.js application as well. For example, [Vuex](https://github.com/vuejs/vuex/) is a Flux-inspired application architecture that is designed specifically for managing state inside large Vue.js applications. [Redux](https://github.com/rackt/redux/), the most popular Flux implementation for React, is view-layer agnostic and can also easily work with Vue via some [simple bindings](https://github.com/egoist/revue).
+Flux 架构常用于 React 应用中,但它的核心理念也可以适用于 Vue.js 应用。比如 [Vuex](https://github.com/vuejs/vuex/) 就是一个借鉴于 Flux,但是专门为 Vue.js 所设计的状态管理方案。React 生态圈中最流行的 Flux 实现 [Redux](https://github.com/rackt/redux/) 也可以通过[简单的绑定](https://github.com/egoist/revue)和 Vue 一起使用。
-## Unit Testing
+## 单元测试
-Anything compatible with a module-based build system works. A recommendation is using the [Karma](http://karma-runner.github.io/0.12/index.html) test runner. It has a lot of community plugins, including support for [Webpack](https://github.com/webpack/karma-webpack) and [Browserify](https://github.com/Nikku/karma-browserify). For detailed setup, please refer to each project's respective documentation.
+任何支持模块构建系统的单元测试工具都可以。推荐使用 [Karma](http://karma-runner.github.io/0.12/index.html)。它有许多插件,支持 [Webpack](https://github.com/webpack/karma-webpack) 和 [Browserify](https://github.com/Nikku/karma-browserify)。用法见它们的文档。
-In terms of code structure for testing, the best practice is to export raw options / functions in your component modules. Consider this example:
+代码测试的最佳实践是导出组件模块的选项/函数。例如:
``` js
// my-component.js
@@ -147,7 +147,7 @@ module.exports = {
}
```
-You can use that file in your entry module like this:
+在入口模块中使用这个模块:
``` js
// main.js
@@ -161,10 +161,10 @@ var app = new Vue({
})
```
-And you can test that module like this:
+测试这个模块:
``` js
-// Some Jasmine 2.0 tests
+// Jasmine 2.0 测试
describe('my-component', function () {
// require source module
var myComponent = require('../src/my-component')
@@ -179,17 +179,17 @@ describe('my-component', function () {
})
```
-There are example Karma configurations for both [Webpack](https://github.com/vuejs/vue-loader-example/blob/master/build/karma.conf.js) and [Browserify](https://github.com/vuejs/vueify-example/blob/master/karma.conf.js).
+Karma 的示例配置:[Webpack](https://github.com/vuejs/vue-loader-example/blob/master/build/karma.conf.js), [Browserify](https://github.com/vuejs/vueify-example/blob/master/karma.conf.js)。
-
Since Vue.js directives perform updates asynchronously, when you are asserting DOM state after changing the data, you will have to do so in a `Vue.nextTick` callback.
+
因为 Vue.js 指令是异步更新,如果想在修改数据之后修改 DOM ,应当在 `Vue.nextTick` 的回调中操作。
-## Deploying for Production
+## 生产发布
-The minified standalone build of Vue.js has already stripped out all the warnings for you for a smaller file size, but when you are using tools like Browserify or Webpack to build Vue.js applications, you will need some additional configuration to achieve this.
+为了更小的文件体积,Vue.js 的压缩版本删除所有的警告,但是在使用 Browserify 或 Webpack 等工具构建 Vue.js 应用时,压缩需要一些配置。
### Webpack
-Use Webpack's [DefinePlugin](http://webpack.github.io/docs/list-of-plugins.html#defineplugin) to indicate a production environment, so that warning blocks can be automatically dropped by UglifyJS during minification. Example config:
+使用插件 [DefinePlugin](http://webpack.github.io/docs/list-of-plugins.html#defineplugin) 将当前环境指定为生产环境,警告将在 UglifyJS 压缩代码过程中被删除。配置示例:
``` js
var webpack = require('webpack')
@@ -214,12 +214,12 @@ module.exports = {
### Browserify
-Just run your bundling command with `NODE_ENV` set to `"production"`. Vue automatically applies [envify](https://github.com/hughsk/envify) transform to itself and makes warning blocks unreachable. For example:
+将 NODE_ENV 设置为 "production",然后运行打包命令。Vue 会自动应用 [envify](https://github.com/hughsk/envify) 并让警告块不能运行。例如:
``` bash
NODE_ENV=production browserify -e main.js | uglifyjs -c -m > build.js
```
-## An App Example
+## 应用示例
-The [Vue.js Hackernews Clone](https://github.com/vuejs/vue-hackernews) is an example application that uses Webpack + vue-loader for code organization, vue-router for routing, and HackerNews' official Firebase API as the backend. It's by no means a big application, but it demonstrates the combined usage of the concepts discussed on this page.
+[Vue.js Hackernews Clone](https://github.com/vuejs/vue-hackernews) 这个应用示例使用 Webpack + vue-loader 组织代码,使用 vue-router 作为路由器,HackerNews 官方的 Firebase API 作为后端。它当然不是大应用,但是它综合演示了本页讨论的概念。
diff --git a/src/guide/class-and-style.md b/src/guide/class-and-style.md
index c5670f4a0..c59caffa3 100644
--- a/src/guide/class-and-style.md
+++ b/src/guide/class-and-style.md
@@ -1,18 +1,18 @@
---
-title: Class and Style Bindings
+title: Class 与 Style 绑定
type: guide
order: 6
---
-A common need for data binding is manipulating an element's class list and its inline styles. Since they are both attributes, we can use `v-bind` to handle them: we just need to calculate a final string with our expressions. However, meddling with string concatenation is annoying and error-prone. For this reason, Vue.js provides special enhancements when `v-bind` is used for `class` and `style`. In addition to Strings, the expressions can also evaluate to Objects or Arrays.
+数据绑定一个常见需求是操作元素的 class 列表和它的内联样式。因为它们都是 attribute,我们可以用 `v-bind` 处理它们:只需要计算出表达式最终的字符串。不过,字符串拼接麻烦又易错。因此,在 `v-bind` 用于 `class` 和 `style` 时,Vue.js 专门增强了它。表达式的结果类型除了字符串之外,还可以是对象或数组。
-## Binding HTML Classes
+## 绑定 HTML Class
-
Although you can use mustache interpolations such as `{% raw %}class="{{ className }}"{% endraw %}` to bind the class, it is not recommended to mix that style with `v-bind:class`. Use one or the other!
-### Object Syntax
+### 对象语法
-We can pass an Object to `v-bind:class` to dynamically toggle classes. Note the `v-bind:class` directive can co-exist with the plain `class` attribute:
+我们可以传给 `v-bind:class` 一个对象,以动态地切换 class。注意 `v-bind:class` 指令可以与普通的 `class` 特性共存:
``` html
@@ -24,15 +24,15 @@ data: {
}
```
-Which will render:
+渲染为:
``` html
```
-When `isA` and `isB` changes, the class list will be updated accordingly. For example, if `isB` becomes `true`, the class list will become `"static class-a class-b"`.
+当 `isA` 和 `isB` 变化时,class 列表将相应地更新。例如,如果 `isB` 变为 `true`,class 列表将变为 `"static class-a class-b"`。
-And you can directly bind to an object in data as well:
+你也可以直接绑定数据里的一个对象:
``` html
@@ -46,11 +46,11 @@ data: {
}
```
-This will render the same result. As you may have noticed, we can also bind to a [computed property](computed.html) that returns an Object. This is a common and powerful pattern.
+我们也可以在这里绑定一个返回对象的[计算属性](computed.html)。这是一个常用且强大的模式。
-### Array Syntax
+### 数组语法
-We can pass an Array to `v-bind:class` to apply a list of classes:
+我们可以把一个数组传给 `v-bind:class`,以应用一个 class 列表:
``` html
@@ -62,31 +62,32 @@ data: {
}
```
-Which will render:
+渲染为:
``` html
```
-If you would like to also toggle a class in the list conditionally, you can do it with a ternary expression:
+如果你也想根据条件切换列表中的 class,可以用三元表达式:
``` html
```
-This will always apply `classA`, but will only apply `classB` when `isB` is `true`.
+此例始终添加 `classA`,但是只有在 `isB` 是 `true` 时添加 `classB` 。
-However, this can be a bit verbose if you have multiple conditional classes. In version 1.0.19+, it's also possible to use the Object syntax inside Array syntax:
+不过,当有多个条件 class 时这样写有些繁琐。在 1.0.19+ 中,可以在数组语法中使用对象语法:
``` html
```
-## Binding Inline Styles
-### Object Syntax
+## 绑定内联样式
-The Object syntax for `v-bind:style` is pretty straightforward - it looks almost like CSS, except it's a JavaScript object. You can use either camelCase or kebab-case for the CSS property names:
+### 对象语法
+
+`v-bind:style` 的对象语法十分直观——看着非常像 CSS,其实它是一个 JavaScript 对象。CSS 属性名可以用驼峰式(camelCase)或短横分隔命名(kebab-case):
``` html
@@ -98,7 +99,7 @@ data: {
}
```
-It is often a good idea to bind to a style object directly so that the template is cleaner:
+直接绑定到一个样式对象通常更好,让模板更清晰:
``` html
@@ -112,16 +113,16 @@ data: {
}
```
-Again, the Object syntax is often used in conjunction with computed properties that return Objects.
+同样的,对象语法常常结合返回对象的计算属性使用。
-### Array Syntax
+### 数组语法
-The Array syntax for `v-bind:style` allows you to apply multiple style objects to the same element:
+`v-bind:style` 的数组语法可以将多个样式对象应用到一个元素上:
``` html
```
-### Auto-prefixing
+### 自动添加前缀
-When you use a CSS property that requires vendor prefixes in `v-bind:style`, for example `transform`, Vue.js will automatically detect and add appropriate prefixes to the applied styles.
+当 `v-bind:style` 使用需要厂商前缀的 CSS 属性时,如 `transform`,Vue.js 会自动侦测并添加相应的前缀。
diff --git a/src/guide/comparison.md b/src/guide/comparison.md
index 445e1b607..a9f270c3e 100644
--- a/src/guide/comparison.md
+++ b/src/guide/comparison.md
@@ -1,75 +1,75 @@
---
-title: Comparison with Other Frameworks
+title: 对比其它框架
type: guide
order: 19
---
## Angular
-There are a few reasons to use Vue over Angular, although they might not apply for everyone:
+选择 Vue 而不选择 Angular,有下面几个原因,当然不是对每个人都适合:
-- Vue.js is much simpler than Angular, both in terms of API and design. You can learn almost everything about it really fast and get productive.
+- 在 API 与设计两方面上 Vue.js 都比 Angular 简单得多,因此你可以快速地掌握它的全部特性并投入开发。
-- Vue.js is a more flexible, less opinionated solution. That allows you to structure your app the way you want it to be, instead of being forced to do everything the Angular way. It's only an interface layer so you can use it as a light feature in pages instead of a full blown SPA. It gives you bigger room to mix and match with other libraries, but you are also responsible for making more architectural decisions. For example, Vue.js' core doesn't come with routing or ajax functionalities by default, and usually assumes you are building the application using an external module bundler. This is probably the most important distinction.
+- Vue.js 是一个更加灵活开放的解决方案。它允许你以希望的方式组织应用程序,而不是任何时候都必须遵循 Angular 制定的规则。它仅仅是一个视图层,所以你可以将它嵌入一个现有页面而不一定要做成一个庞大的单页应用。在配合其他库方面它给了你更大的的空间,但相应,你也需要做更多的架构决策。例如,Vue.js 核心默认不包含路由和 Ajax 功能,并且通常假定你在应用中使用了一个模块构建系统。这可能是最重要的区别。
-- Angular uses two-way binding between scopes. While Vue also supports explicit two-way bindings, it defaults to a one-way, parent-to-child data flow between components. Using one-way binding makes the flow of data easier to reason about in large apps.
+- Angular 使用双向绑定,Vue 也支持双向绑定,不过默认为单向绑定,数据从父组件单向传给子组件。在大型应用中使用单向绑定让数据流易于理解。
-- Vue.js has a clearer separation between directives and components. Directives are meant to encapsulate DOM manipulations only, while Components stand for a self-contained unit that has its own view and data logic. In Angular there's a lot of confusion between the two.
+- 在 Vue.js 中指令和组件分得更清晰。指令只封装 DOM 操作,而组件代表一个自给自足的独立单元 —— 有自己的视图和数据逻辑。在 Angular 中两者有不少相混的地方。
-- Vue.js has better performance and is much, much easier to optimize, because it doesn't use dirty checking. Angular gets slow when there are a lot of watchers, because every time anything in the scope changes, all these watchers need to be re-evaluated again. Also, the digest cycle may have to run multiple times to "stabilize" if some watcher triggers another update. Angular users often have to resort to esoteric techniques to get around the digest cycle, and in some situations there's simply no way to optimize a scope with a large amount of watchers. Vue.js doesn't suffer from this at all because it uses a transparent dependency-tracking observing system with async queueing - all changes trigger independently unless they have explicit dependency relationships. The only optimization hint you'll ever need is the `track-by` param on `v-for` lists.
+- Vue.js 有更好的性能,并且非常非常容易优化,因为它不使用脏检查。Angular,当 watcher 越来越多时会变得越来越慢,因为作用域内的每一次变化,所有 watcher 都要重新计算。并且,如果一些 watcher 触发另一个更新,脏检查循环(digest cycle)可能要运行多次。 Angular 用户常常要使用深奥的技术,以解决脏检查循环的问题。有时没有简单的办法来优化有大量 watcher 的作用域。Vue.js 则根本没有这个问题,因为它使用基于依赖追踪的观察系统并且异步列队更新,所有的数据变化都是独立地触发,除非它们之间有明确的依赖关系。唯一需要做的优化是在 `v-for` 上使用 `track-by`。
-Interestingly, there are quite some similarities in how Angular 2 and Vue are addressing these Angular 1 issues.
+有意思的是,Angular 2 和 Vue 用相似的设计解决了一些 Angular 1 中存在的问题。
## React
-React and Vue.js do share a similarity in that they both provide reactive & composable View components. There are, of course, many differences as well.
+React.js 和 Vue.js 确实有一些相似 —— 它们都提供数据驱动、可组合搭建的视图组件。当然它们也有许多不同。
-First, the internal implementation is fundamentally different. React's rendering leverages the Virtual DOM - an in-memory representation of what the actual DOM should look like. When the state changes, React does a full re-render of the Virtual DOM, diffs it, and then patches the real DOM.
+首先,内部实现本质上不同。React 的渲染建立在 Virtual DOM 上——一种在内存中描述 DOM 树状态的数据结构。当状态发生变化时,React 重新渲染 Virtual DOM,比较计算之后给真实 DOM 打补丁。
-The virtual-DOM approach provides a functional way to describe your view at any point of time, which is really nice. Because it doesn't use observables and re-renders the entire app on every update, the view is by definition guaranteed to be in sync with the data. It also opens up possibilities to isomorphic JavaScript applications.
+Virtual DOM 提供了一个函数式的方法描述视图,这真的很棒。因为它不使用数据观察机制,每次更新都会重新渲染整个应用,因此从定义上保证了视图与数据的同步。它也开辟了 JavaScript 同构应用的可能性。
-Instead of a Virtual DOM, Vue.js uses the actual DOM as the template and keeps references to actual nodes for data bindings. This limits Vue.js to environments where DOM is present. However, contrary to the common misconception that Virtual-DOM makes React faster than anything else, Vue.js actually out-performs React when it comes to hot updates, and requires almost no hand-tuned optimization. With React, you need to implement `shouldComponentUpdate` everywhere and use immutable data structures to achieve fully optimized re-renders.
+Vue.js 不使用 Virtual DOM 而是使用真实 DOM 作为模板,数据绑定到真实节点。Vue.js 的应用环境必须提供 DOM。但是,相对于常见的误解——Virtual DOM 让 React 比其它的都快, Vue.js 实际上性能比 React 好,而且几乎不用手工优化。而 React,为了最优化的渲染需要处处实现 `shouldComponentUpdate` 和使用不可变数据结构。
-API-wise, one issue with React (or JSX) is that the render function often involves a lot of logic, and ends up looking more like a piece of program (which in fact it is) rather than a visual representation of the interface. For some developers this is a bonus, but for designer/developer hybrids like me, having a template makes it much easier to think visually about the design and CSS. JSX mixed with JavaScript logic breaks that visual model I need to map the code to the design. In contrast, Vue.js pays the cost of a lightweight data-binding DSL so that we have a visually scannable template and with logic encapsulated into directives and filters.
+在 API 方面,React(或 JSX)的一个问题是,渲染函数常常包含大量的逻辑,最终看着更像是程序片断(实际上就是)而不是界面的视觉呈现。对于部分开发者来说,他们可能觉得这是个优点,但对那些像我一样兼顾设计和开发的人来说,模板能让我们更好地在视觉上思考设计和 CSS。JSX 和 JavaScript 逻辑的混合干扰了我将代码映射到设计的思维过程。相反,Vue.js 通过在模板中加入一个轻量级的 DSL (指令系统),换来一个依旧直观的模板,且能将逻辑封装进指令和过滤器中。
-Another issue with React is that because DOM updates are completely delegated to the Virtual DOM, it's a bit tricky when you actually **want** to control the DOM yourself (although theoretically you can, you'd be essentially working against the library when you do that). For applications that need ad-hoc custom DOM manipulations, especially animations with complex timing requirements, this can become a pretty annoying restriction. On this front, Vue.js allows for more flexibility and there are [multiple FWA/Awwwards winning sites](https://github.com/vuejs/awesome-vue#interactive-experiences) built with Vue.js.
+React 的另一个问题是:由于 DOM 更新完全交给 Virtual DOM 管理,当想要自己控制 DOM 时就有点棘手了(虽然理论上可以做到,但是这样做就本质上违背了 React 的设计思想)。如果应用需要特别的自定义 DOM 操作,特别是复杂时间控制的动画,这个限制就很讨厌。在这方面,Vue.js 更灵活,有许多用 Vue.js 制作的 [FWA/Awwwards 获奖站点](https://github.com/vuejs/awesome-vue#interactive-experiences)。
-Some additional notes:
+再多说几句:
-- The React team has very ambitious goals in making React a platform-agnostic UI development paradigm, while Vue is focused on providing a pragmatic solution for the web.
+- React 团队雄心勃勃,计划让 React 成为通用平台的 UI 开发工具,而 Vue 专注于为 Web 提供实用的解决方案。
-- React, due to its functional nature, plays very well with functional programming patterns. However it also introduces a higher learning barrier for junior developers and beginners. Vue is much easier to pick up and get productive with in this regard.
+- React,由于它的函数式特质,可以很好地使用函数式编程模式。但是对于初级开发者和初学者这也导致较大的学习难度。Vue 更易学习并能快速投入开发。
-- For large applications, the React community has been doing a lot of innovation in terms of state management solutions, e.g. Flux/Redux. Vue itself doesn't really address that problem (same for React core), but the state management patterns can be easily adopted for a similar architecture. Vue has its own state management solution called [Vuex](https://github.com/vuejs/vuex), and it's also possible to [use Redux with Vue](https://github.com/egoist/revue).
+- 对于大型应用,React 社区已经创造了大量的状态管理方案,例如 Flux/Redux。Vue 本身不解决这个问题(React 内核也是),但是可以轻松地修改状态管理模式,实现一个类似的架构。Vue 有自己的状态管理方案 [Vuex](https://github.com/vuejs/vuex),而且 Vue 也可以与 [Redux](https://github.com/egoist/revue) 一起用。
-- The trend in React development is pushing you to put everything in JavaScript, including your CSS. There has been many CSS-in-JS solutions out there but all more or less have its own problems. And most importantly, it deviates from the standard CSS authoring experience and makes it very awkward to leverage existing work in the CSS community. Vue's [single file components](/guide/application.html#Single-File-Components) gives you component-encapsulated CSS while still allowing you to use your pre-processors of choice.
+- React 的开发趋势是将所有东西都放在 JavaScript 中,包括 CSS。已经有许多 CSS-in-JS 方案,但是所有的方案多多少少都有它的问题。而且更重要的是,这么做脱离了标准的 CSS 开发经验,并且很难和 CSS 社区的已有工作配合。Vue 的 [单文件组件](/guide/application.html#单文件组件) 在把 CSS 封装到组件模块的同时仍然允许你使用你喜欢的预处理器。
## Ember
-Ember is a full-featured framework that is designed to be highly opinionated. It provides a lot of established conventions, and once you are familiar enough with them, it can make you very productive. However, it also means the learning curve is high and the flexibility suffers. It's a trade-off when you try to pick between an opinionated framework and a library with a loosely coupled set of tools that work together. The latter gives you more freedom but also requires you to make more architectural decisions.
+Ember 是一个全能框架。它提供大量的约定,一旦你熟悉了它们,开发会很高效。不过,这也意味着学习曲线较高,而且不灵活。在框架和库(加上一系列松散耦合的工具)之间权衡选择。后者更自由,但是也要求你做更多的架构决定。
-That said, it would probably make a better comparison between Vue.js core and Ember's templating and object model layer:
+也就是说,最好比较 Vue.js 内核和 Ember 的模板与数据模型层:
-- Vue provides unobtrusive reactivity on plain JavaScript objects, and fully automatic computed properties. In Ember you need to wrap everything in Ember Objects and manually declare dependencies for computed properties.
+- Vue 在普通 JavaScript 对象上建立响应,提供自动化的计算属性。在 Ember 中需要将所有东西放在 Ember 对象内,并且手工为计算属性声明依赖。
-- Vue's template syntax harnesses the full power of JavaScript expressions, while Handlebars' expression and helper syntax is quite limited in comparison.
+- Vue 的模板语法可以用全功能的 JavaScript 表达式,而 Handlebars 的语法和帮助函数语法相比之下非常受限。
-- Performance wise, Vue outperforms Ember by a fair margin, even after the latest Glimmer engine update in Ember 2.0. Vue automatically batches updates, while in Ember you need to manually manage run loops in performance-critical situations.
+- 在性能上,Vue 甩开 Ember 几条街,即使是 Ember 2.0 最新的 Glimmer 引擎。Vue 自动批量更新,在性能比较关键时 Ember 要手工管理循环。
## Polymer
-Polymer is yet another Google-sponsored project and in fact was a source of inspiration for Vue.js as well. Vue.js' components can be loosely compared to Polymer's custom elements, and both provide a very similar development style. The biggest difference is that Polymer is built upon the latest Web Components features, and requires non-trivial polyfills to work (with degraded performance) in browsers that don't support those features natively. In contrast, Vue.js works without any dependencies down to IE9.
+Polymer 是另一个由 Google 支持的项目,实际上也是 Vue.js 的灵感来源之一。Vue.js 的组件可以类比为 Polymer 中的自定义元素,它们提供类似的开发体验。最大的不同在于,Polymer 依赖最新的 Web 组件特性,在不支持的浏览器中,需要加载笨重的 polyfill,性能也会受到影响。相对的,Vue.js 无需任何依赖,最低兼容到IE9。
-Also, in Polymer 1.0 the team has really made its data-binding system very limited in order to compensate for the performance. For example, the only expressions supported in Polymer templates are the boolean negation and single method calls. Its computed property implementation is also not very flexible.
+另外,在 Polymer 1.0 中,为了性能开发团队严格限制了它的数据绑定系统。例如,Polymer 模板支持的表达式仅有逻辑逆运算和简单的方法调用。它的计算属性实现得也不是很灵活。
-Finally, when deploying to production, Polymer elements need to be bundled via a Polymer-specific tool called vulcanizer. In comparison, single file Vue components can leverage everything the Webpack ecosystem has to offer, and thus you can easily use ES6 and any CSS pre-processors you want in your Vue components.
+最后,当发布到生产环境时,Polymer 元素需要用专用工具 vulcanizer 打包。相比之下,单文件 Vue 组件能与 Webpack 无缝整合,因而你可以轻松在组件中使用 ES6 及任意 CSS 预处理器。
## Riot
-Riot 2.0 provides a similar component-based development model (which is called a "tag" in Riot), with a minimal and beautifully designed API. I think Riot and Vue share a lot in design philosophies. However, despite being a bit heavier than Riot, Vue does offer some significant advantages over Riot:
+Riot 2.0 提供类似的基于组件的开发模式(Riot 称之为“标签”),API 小而美。我认为 Riot 与 Vue 在设计思路上有许多相同点。不过,尽管比 Riot 重一点,Vue 提供了一些显著优处:
-- True conditional rendering (Riot renders all if branches and simply show/hide them)
-- A far-more powerful router (Riot’s routing API is just way too minimal)
-- More mature tooling support (see webpack + vue-loader)
-- Transition effect system (Riot has none)
-- Better performance. (Riot in fact uses dirty checking rather than a virtual-dom, and thus suffers from the same performance issues as Angular.)
+- 真实的条件渲染,Riot 渲染所有的分支,然后简单地显示/隐藏它们。
+- 一个强大得多的路由器,Riot 的路由 API 过于简陋。
+- 更成熟的工具链支持,见 Webpack + vue-loader。
+- 过渡效果系统,Riot 没有。
+- 更佳的性能。Riot 实际上使用脏检查而不是 Virtual DOM,因而遭受跟 Angular 一样的性能问题。
diff --git a/src/guide/components.md b/src/guide/components.md
index e22242a57..f94ee1a03 100644
--- a/src/guide/components.md
+++ b/src/guide/components.md
@@ -1,35 +1,35 @@
---
-title: Components
+title: 组件
type: guide
order: 12
---
-## What are Components?
+## 什么是组件?
-Components are one of the most powerful features of Vue.js. They help you extend basic HTML elements to encapsulate reusable code. At a high level, Components are custom elements that Vue.js’ compiler would attach specified behavior to. In some cases, they may also appear as a native HTML element extended with the special `is` attribute.
+组件(Component)是 Vue.js 最强大的功能之一。组件可以扩展 HTML 元素,封装可重用的代码。在较高层面上,组件是自定义元素,Vue.js 的编译器为它添加特殊功能。在有些情况下,组件也可以是原生 HTML 元素的形式,以 `is` 特性扩展。
-## Using Components
+## 使用组件
-### Registration
+### 注册
-We've learned in the previous sections that we can create a component constructor using `Vue.extend()`:
+之前说过,我们可以用 `Vue.extend()` 创建一个组件构造器:
``` js
var MyComponent = Vue.extend({
- // options...
+ // 选项...
})
```
-To use this constructor as a component, you need to **register** it with `Vue.component(tag, constructor)`:
+要把这个构造器用作组件,需要用 `Vue.component(tag, constructor)` **注册** :
``` js
-// Globally register the component with tag: my-component
+// 全局注册组件,tag 为 my-component
Vue.component('my-component', MyComponent)
```
-
Note that Vue.js does not enforce the [W3C rules](http://www.w3.org/TR/custom-elements/#concepts) for custom tag-names (all-lowercase, must contain a hyphen) though following this convention is considered good practice.
-Once registered, the component can now be used in a parent instance's template as a custom element, ``. Make sure the component is registered **before** you instantiate your root Vue instance. Here's the full example:
+组件在注册之后,便可以在父实例的模块中以自定义元素 `` 的形式使用。要确保在初始化根实例**之前**注册了组件:
``` html
@@ -38,21 +38,21 @@ Once registered, the component can now be used in a parent instance's template a
```
``` js
-// define
+// 定义
var MyComponent = Vue.extend({
template: '
A custom component!
'
})
-// register
+// 注册
Vue.component('my-component', MyComponent)
-// create a root instance
+// 创建根实例
new Vue({
el: '#example'
})
```
-Which will render:
+渲染为:
``` html
@@ -72,11 +72,11 @@ new Vue({ el: '#example' })
{% endraw %}
-Note the component's template **replaces** the custom element, which only serves as a **mounting point**. This behavior can be configured using the `replace` instance option.
+注意组件的模板**替换**了自定义元素,自定义元素的作用只是作为一个**挂载点**。可以用实例选项 `replace` 决定是否替换。
-### Local Registration
+### 局部注册
-You don't have to register every component globally. You can make a component available only in the scope of another component by registering it with the `components` instance option:
+不需要全局注册每个组件。可以让组件只能用在其它组件内,用实例选项 `components` 注册:
``` js
var Child = Vue.extend({ /* ... */ })
@@ -84,25 +84,25 @@ var Child = Vue.extend({ /* ... */ })
var Parent = Vue.extend({
template: '...',
components: {
- // will only be available in Parent's template
+ // 只能用在父组件模板内
'my-component': Child
}
})
```
-The same encapsulation applies for other assets types such as directives, filters and transitions.
+这种封装也适用于其它资源,如指令、过滤器和过渡。
-### Registration Sugar
+### 注册语法糖
-To make things easier, you can directly pass in the options object instead of an actual constructor to `Vue.component()` and the `component` option. Vue.js will automatically call `Vue.extend()` for you under the hood:
+为了让事件更简单,可以直接传入选项对象而不是构造器给 `Vue.component()` 和 `component` 选项。Vue.js 在背后自动调用 `Vue.extend()`:
``` js
-// extend and register in one step
+// 在一个步骤中扩展与注册
Vue.component('my-component', {
template: '
A custom component!
'
})
-// also works for local registration
+// 局部注册也可以这么做
var Parent = Vue.extend({
components: {
'my-component': {
@@ -112,9 +112,9 @@ var Parent = Vue.extend({
})
```
-### Component Option Caveats
+### 组件选项问题
-Most of the options that can be passed into the Vue constructor can be used in `Vue.extend()`, with two special cases: `data` and `el`. Imagine we simply pass an object as `data` to `Vue.extend()`:
+传入 Vue 构造器的多数选项也可以用在 `Vue.extend()` 中,不过有两个特例: `data` 和 `el`。试想如果我们简单地把一个对象作为 `data` 选项传给 `Vue.extend()`:
``` js
var data = { a: 1 }
@@ -123,7 +123,7 @@ var MyComponent = Vue.extend({
})
```
-The problem with this is that the same `data` object will be shared across all instances of `MyComponent`! This is most likely not what we want, so we should use a function that returns a fresh object as the `data` option:
+这么做的问题是 `MyComponent` 所有的实例将共享同一个 `data` 对象!这基本不是我们想要的,因此我们应当使用一个函数作为 `data` 选项,让这个函数返回一个新对象:
``` js
var MyComponent = Vue.extend({
@@ -133,23 +133,24 @@ var MyComponent = Vue.extend({
})
```
-The `el` option also requires a function value when used in `Vue.extend()`, for exactly the same reason.
+同理,`el` 选项用在 `Vue.extend()` 中时也须是一个函数。
-### Template Parsing
+### 模板解析
-Vue.js template engine is DOM-based and uses native parser that comes with the browser instead of providing a custom one. There are benefits to this approach when compared to string-based template engines, but there are also caveats. Templates have to be individually valid pieces of HTML. Some HTML elements have restrictions on what elements can appear inside them. Most common of these restrictions are:
+Vue 的模板是 DOM 模板,使用浏览器原生的解析器而不是自己实现一个。相比字符串模板,DOM 模板有一些好处,但是也有问题,它必须是有效的 HTML 片段。一些 HTML 元素对什么元素可以放在它里面有限制。常见的限制:
-- `a` can not contain other interactive elements (e.g. buttons and other links)
-- `li` should be a direct child of `ul` or `ol`, and both `ul` and `ol` can only contain `li`
-- `option` should be a direct child of `select`, and `select` can only contain `option` (and `optgroup`)
-- `table` can only contain `thead`, `tbody`, `tfoot` and `tr`, and these elements should be direct children of `table`
-- `tr` can only contain `th` and `td`, and these elements should be direct children of `tr`
+- `a` 不能包含其它的交互元素(如按钮,链接)
+- `ul` 和 `ol` 只能直接包含 `li`
+- `select` 只能包含 `option` 和 `optgroup`
+- `table` 只能直接包含 `thead`, `tbody`, `tfoot`, `tr`, `caption`, `col`, `colgroup`
+- `tr` 只能直接包含 `th` 和 `td`
-In practice these restriction can cause unexpected behavior. Although in simple cases it might appear to work, you can not rely on custom elements being expanded before browser validation. E.g. `` is not a valid template even if `my-select` component eventually expands to ``.
-Another consequence is that you can not use custom tags (including custom elements and special tags like ``, `` and ``) inside of `ul`, `select`, `table` and other elements with similar restrictions. Custom tags will be hoisted out and thus not render properly.
+在实际中,这些限制会导致意外的结果。尽管在简单的情况下它可能可以工作,但是你不能依赖自定义组件在浏览器验证之前的展开结果。例如 `` 不是有效的模板,即使 `my-select` 组件最终展开为 ``。
-In case of a custom element you should use the `is` special attribute:
+另一个结果是,自定义标签(包括自定义元素和特殊标签,如 ``、``、 `` )不能用在 `ul`, `select`, `table` 等对内部元素有限制的标签内。放在这些元素内部的自定义标签将被提到元素的外面,因而渲染不正确。
+
+对于自定义元素,应当使用 `is` 特性:
``` html
@@ -157,7 +158,7 @@ In case of a custom element you should use the `is` special attribute:
```
-In case of a `` inside of a `
` you should use ``, as tables are allowed to have multiple `tbody`:
+`` 不能用在 `
` 内,这时应使用 ``,`
` 可以有多个 ``:
``` html
@@ -170,29 +171,29 @@ In case of a `` inside of a `
` you should use ``, as tab
## Props
-### Passing Data with Props
+### 使用 Props 传递数据
-Every component instance has its own **isolated scope**. This means you cannot (and should not) directly reference parent data in a child component's template. Data can be passed down to child components using **props**.
+**组件实例的作用域是孤立的**。这意味着不能并且不应该在子组件的模板内直接引用父组件的数据。可以使用 **props** 把数据传给子组件。
-A "prop" is a field on a component's data that is expected to be passed down from its parent component. A child component needs to explicitly declare the props it expects to receive using the [`props` option](/api/#props):
+"prop" 是组件数据的一个字段,期望从父组件传下来。子组件需要显式地用 [`props` 选项](/api/#props) 声明 props:
``` js
Vue.component('child', {
- // declare the props
+ // 声明 props
props: ['msg'],
- // the prop can be used inside templates, and will also
- // be set as `this.msg`
+ // prop 可以用在模板内
+ // 可以用 `this.msg` 设置
template: '{{ msg }}'
})
```
-Then, we can pass a plain string to it like so:
+然后向它传入一个普通字符串:
``` html
```
-**Result:**
+**结果:**
{% raw %}
@@ -213,7 +214,7 @@ new Vue({
### camelCase vs. kebab-case
-HTML attributes are case-insensitive. When using camelCased prop names as attributes, you need to use their kebab-case (hyphen-delimited) equivalents:
+HTML 特性不区分大小写。名字形式为 camelCase 的 prop 用作特性时,需要转为 kebab-case(短横线隔开):
``` js
Vue.component('child', {
@@ -228,9 +229,9 @@ Vue.component('child', {
```
-### Dynamic Props
+### 动态 Props
-Similar to binding a normal attribute to an expression, we can also use `v-bind` for dynamically binding props to data on the parent. Whenever the data is updated in the parent, it will also flow down to the child:
+类似于用 `v-bind` 绑定 HTML 特性到一个表达式,也可以用 `v-bind` 绑定动态 Props 到父组件的数据。每当父组件的数据变化时,也会传导给子组件:
``` html
@@ -240,13 +241,13 @@ Similar to binding a normal attribute to an expression, we can also use `v-bind`
```
-It is often simpler to use the shorthand syntax for `v-bind`:
+使用 `v-bind` 的缩写语法通常更简单:
``` html
```
-**Result:**
+**结果:**
{% raw %}
@@ -270,100 +271,99 @@ new Vue({
{% endraw %}
-### Literal vs. Dynamic
+### 字面量语法 vs. 动态语法
-A common mistake beginners tend to make is attempting to pass down a number using the literal syntax:
+初学者常犯的一个错误是使用字面量语法传递数值:
``` html
-
+
```
-However, since this is a literal prop, its value is passed down as a plain string `"1"`, instead of an actual number. If we want to pass down an actual JavaScript number, we need to use the dynamic syntax to make its value be evaluated as a JavaScript expression:
+因为它是一个字面 prop,它的值以字符串 `"1"` 而不是以实际的数字传下去。如果想传递一个实际的 JavaScript 数字,需要使用动态语法,从而让它的值被当作 JavaScript 表达式计算:
``` html
-
+
```
-### Prop Binding Types
+### Prop 绑定类型
-By default, all props form a **one-way-down** binding between the child property and the parent one: when the parent property updates, it will flow down to the child, but not the other way around. This default is meant to prevent child components from accidentally mutating the parent's state, which can make your app's data flow harder to reason about. However, it is also possible to explicitly enforce a two-way or a one-time binding with the `.sync` and `.once` **binding type modifiers**:
+prop 默认是**单向**绑定:当父组件的属性变化时,将传导给子组件,但是反过来不会。这是为了防止子组件无意修改了父组件的状态——这会让应用的数据流难以理解。不过,也可以使用 `.sync` 或 `.once` **绑定修饰符**显式地强制双向或单次绑定:
-Compare the syntax:
+比较语法:
``` html
-
+
-
+
-
+
```
-The two-way binding will sync the change of child's `msg` property back to the parent's `parentMsg` property. The one-time binding, once set up, will not sync future changes between the parent and the child.
+双向绑定会把子组件的 `msg` 属性同步回父组件的 `parentMsg` 属性。单次绑定在建立之后不会同步之后的变化。
-
Note that if the prop being passed down is an Object or an Array, it is passed by reference. Mutating the Object or Array itself inside the child **will** affect parent state, regardless of the binding type you are using.
-### Prop Validation
+### Prop 验证
-It is possible for a component to specify the requirements for the props it is receiving. This is useful when you are authoring a component that is intended to be used by others, as these prop validation requirements essentially constitute your component's API, and ensure your users are using your component correctly. Instead of defining the props as an array of strings, you can use the object hash format that contain validation requirements:
+组件可以为 props 指定验证要求。当组件给其他人使用时这很有用,因为这些验证要求构成了组件的 API,确保其他人正确地使用组件。此时 props 的值是一个对象,包含验证要求:
``` js
Vue.component('example', {
props: {
- // basic type check (`null` means accept any type)
+ // 基础类型检测 (`null` 意思是任何类型都可以)
propA: Number,
- // multiple possible types (1.0.21+)
+ // 多种类型 (1.0.21+)
propM: [String, Number],
- // a required string
+ // 必需且是字符串
propB: {
type: String,
required: true
},
- // a number with default value
+ // 数字,有默认值
propC: {
type: Number,
default: 100
},
- // object/array defaults should be returned from a
- // factory function
+ // 对象/数组的默认值应当由一个函数返回
propD: {
type: Object,
default: function () {
return { msg: 'hello' }
}
},
- // indicate this prop expects a two-way binding. will
- // raise a warning if binding type does not match.
+ // 指定这个 prop 为双向绑定
+ // 如果绑定类型不对将抛出一条警告
propE: {
twoWay: true
},
- // custom validator function
+ // 自定义验证函数
propF: {
validator: function (value) {
return value > 10
}
},
- // coerce function (new in 1.0.12)
- // cast the value before setting it on the component
+ // 转换函数(1.0.12 新增)
+ // 在设置值之前转换值
propG: {
coerce: function (val) {
- return val + '' // cast the value to string
+ return val + '' // 将值转换为字符串
}
},
propH: {
coerce: function (val) {
- return JSON.parse(val) // cast the value to Object
+ return JSON.parse(val) // 将 JSON 字符串转换为对象
}
}
}
})
```
-The `type` can be one of the following native constructors:
+`type` 可以是下面原生构造器:
- String
- Number
@@ -372,48 +372,48 @@ The `type` can be one of the following native constructors:
- Object
- Array
-In addition, `type` can also be a custom constructor function and the assertion will be made with an `instanceof` check.
+`type` 也可以是一个自定义构造器,使用 `instanceof` 检测。
-When a prop validation fails, Vue will refuse to set the value on the child component, and throw a warning if using the development build.
+当 prop 验证失败了,Vue 将拒绝在子组件上设置此值,如果使用的是开发版本会抛出一条警告。
-## Parent-Child Communication
+## 父子组件通信
-### Parent Chain
+### 父链
-A child component holds access to its parent component as `this.$parent`. A root Vue instance will be available to all of its descendants as `this.$root`. Each parent component has an array, `this.$children`, which contains all its child components.
+子组件可以用 `this.$parent` 访问它的父组件。根实例的后代可以用 `this.$root` 访问它。父组件有一个数组 `this.$children`,包含它所有的子元素。
-Although it's possible to access any instance in the parent chain, you should avoid directly relying on parent data in a child component and prefer passing data down explicitly using props. In addition, it is a very bad idea to mutate parent state from a child component, because:
+尽管可以访问父链上任意的实例,不过子组件应当避免直接依赖父组件的数据,尽量显式地使用 props 传递数据。另外,在子组件中修改父组件的状态是非常糟糕的做法,因为:
-1. It makes the parent and child tightly coupled;
+1. 这让父组件与子组件紧密地耦合;
-2. It makes the parent state much harder to reason about when looking at it alone, because its state may be modified by any child! Ideally, only a component itself should be allowed to modify its own state.
+2. 只看父组件,很难理解父组件的状态。因为它可能被任意子组件修改!理想情况下,只有组件自己能修改它的状态。
-### Custom Events
+### 自定义事件
-All Vue instances implement a custom event interface that facilitates communication within a component tree. This event system is independent from the native DOM events and works differently.
+Vue 实例实现了一个自定义事件接口,用于在组件树中通信。这个事件系统独立于原生 DOM 事件,用法也不同。
-Each Vue instance is an event emitter that can:
+每个 Vue 实例都是一个事件触发器:
-- Listen to events using `$on()`;
+- 使用 `$on()` 监听事件;
-- Trigger events on self using `$emit()`;
+- 使用 `$emit()` 在它上面触发事件;
-- Dispatch an event that propagates upward along the parent chain using `$dispatch()`;
+- 使用 `$dispatch()` 派发事件,事件沿着父链冒泡;
-- Broadcast an event that propagates downward to all descendants using `$broadcast()`.
+- 使用 `$broadcast()` 广播事件,事件向下传导给所有的后代。
-
Unlike DOM events, Vue events will automatically stop propagation after triggering callbacks for the first time along a propagation path, unless the callback explicitly returns `true`.
+
不同于 DOM 事件,Vue 事件在冒泡过程中第一次触发回调之后自动停止冒泡,除非回调明确返回 `true`。
-A simple example:
+简单例子:
``` html
-
+
-
+
Messages: {{ messages | json }}
@@ -421,8 +421,8 @@ A simple example:
```
``` js
-// register child, which dispatches an event with
-// the current message
+// 注册子组件
+// 将当前消息派发出去
Vue.component('child', {
template: '#child-template',
data: function () {
@@ -438,19 +438,17 @@ Vue.component('child', {
}
})
-// bootstrap parent, which pushes message into an array
-// when receiving the event
+// 初始化父组件
+// 将收到消息时将事件推入一个数组
var parent = new Vue({
el: '#events-example',
data: {
messages: []
},
- // the `events` option simply calls `$on` for you
- // when the instance is created
+ // 在创建实例时 `events` 选项简单地调用 `$on`
events: {
'child-msg': function (msg) {
- // `this` in event callbacks are automatically bound
- // to the instance that registered it
+ // 事件回调内的 `this` 自动绑定到注册它的实例上
this.messages.push(msg)
}
}
@@ -497,19 +495,19 @@ var parent = new Vue({
{% endraw %}
-### v-on for Custom Events
+### 使用 v-on 绑定自定义事件
-The example above is pretty nice, but when we are looking at the parent's code, it's not so obvious where the `"child-msg"` event comes from. It would be better if we can declare the event handler in the template, right where the child component is used. To make this possible, `v-on` can be used to listen for custom events when used on a child component:
+上例非常好,不过从父组件的代码中不能直观的看到 `"child-msg"` 事件来自哪里。如果我们在模板中子组件用到的地方声明事件处理器会更好。为此子组件可以用 `v-on` 监听自定义事件:
``` html
```
-This makes things very clear: when the child triggers the `"child-msg"` event, the parent's `handleIt` method will be called. Any code that affects the parent's state will be inside the `handleIt` parent method; the child is only concerned with triggering the event.
+这样就很清楚了:当子组件触发了 `"child-msg"` 事件,父组件的 `handleIt` 方法将被调用。所有影响父组件状态的代码放到父组件的 `handleIt` 方法中;子组件只关注触发事件。
-### Child Component Refs
+### 子组件索引
-Despite the existence of props and events, sometimes you might still need to directly access a child component in JavaScript. To achieve this you have to assign a reference ID to the child component using `v-ref`. For example:
+尽管有 props 和 events,但是有时仍然需要在 JavaScript 中直接访问子组件。为此可以使用 `v-ref` 为子组件指定一个索引 ID。例如:
``` html
@@ -519,15 +517,15 @@ Despite the existence of props and events, sometimes you might still need to dir
``` js
var parent = new Vue({ el: '#parent' })
-// access child component instance
+// 访问子组件
var child = parent.$refs.profile
```
-When `v-ref` is used together with `v-for`, the ref you get will be an Array or an Object containing the child components mirroring the data source.
+`v-ref` 和 `v-for` 一起用时,ref 是一个数组或对象,包含相应的子组件。
-## Content Distribution with Slots
+## 使用 Slot 分发内容
-When using components, it is often desired to compose them like this:
+在使用组件时,常常要像这样组合它们:
``` html
@@ -536,17 +534,17 @@ When using components, it is often desired to compose them like this:
```
-There are two things to note here:
+注意两点:
-1. The `` component does not know what content may be present inside its mount target. It is decided by whatever parent component that is using ``.
+1. `` 组件不知道它的挂载点会有什么内容,挂载点的内容是由 `` 的父组件决定的。
-2. The `` component very likely has its own template.
+2. `` 组件很可能有它自己的模板。
-To make the composition work, we need a way to interweave the parent "content" and the component's own template. This is a process called **content distribution** (or "transclusion" if you are familiar with Angular). Vue.js implements a content distribution API that is modeled after with the current [Web Components spec draft](https://github.com/w3c/webcomponents/blob/gh-pages/proposals/Slots-Proposal.md), using the special `` element to serve as distribution outlets for the original content.
+为了让组件可以组合,我们需要一种方式来混合父组件的内容与子组件自己的模板。这个处理称为**内容分发**(或 "transclusion",如果你熟悉 Angular)。Vue.js 实现了一个内容分发 API,参照了当前 [Web 组件规范草稿](https://github.com/w3c/webcomponents/blob/gh-pages/proposals/Slots-Proposal.md),使用特殊的 `` 元素作为原始内容的插槽。
-### Compilation Scope
+### 编译作用域
-Before we dig into the API, let's first clarify which scope the contents are compiled in. Imagine a template like this:
+在深入内容分发 API 之前,我们先明确内容的编译作用域。假定模板为:
``` html
@@ -554,24 +552,24 @@ Before we dig into the API, let's first clarify which scope the contents are com
```
-Should the `msg` be bound to the parent's data or the child data? The answer is parent. A simple rule of thumb for component scope is:
+`msg` 应该绑定到父组件的数据,还是绑定到子组件的数据?答案是父组件。组件作用域简单地说是:
-> Everything in the parent template is compiled in parent scope; everything in the child template is compiled in child scope.
+> 父组件模板的内容在父组件作用域内编译;子组件模板的内容在子组件作用域内编译
-A common mistake is trying to bind a directive to a child property/method in the parent template:
+一个常见错误是试图在父组件模板内将一个指令绑定到子组件的属性/方法:
``` html
-
+
```
-Assuming `someChildProperty` is a property on the child component, the example above would not work as intended. The parent's template should not be aware of the state of a child component.
+假定 `someChildProperty` 是子组件的属性,上例不会如预期那样工作。父组件模板不应该知道子组件的状态。
-If you need to bind child-scope directives on a component root node, you should do so in the child component's own template:
+如果要绑定子组件内的指令到一个组件的根节点,应当在它的模板内这么做:
``` js
Vue.component('child-component', {
- // this does work, because we are in the right scope
+ // 有效,因为是在正确的作用域内
template: '
Child
',
data: function () {
return {
@@ -581,27 +579,26 @@ Vue.component('child-component', {
})
```
-Similarly, distributed content will be compiled in the parent scope.
+类似地,分发内容是在父组件作用域内编译。
-### Single Slot
+### 单个 Slot
-Parent content will be **discarded** unless the child component template contains at least one `` outlet. When there is only one slot with no attributes, the entire content fragment will be inserted at its position in the DOM, replacing the slot itself.
+父组件的内容将被**抛弃**,除非子组件模板包含 ``。如果子组件模板只有一个没有特性的 slot,父组件的整个内容将插到 slot 所在的地方并替换它。
-Anything originally inside the `` tags is considered **fallback content**. Fallback content is compiled in the child scope and will only be displayed if the hosting element is empty and has no content to be inserted.
+`` 标签的内容视为**回退内容**。回退内容在子组件的作用域内编译,当宿主元素为空并且没有内容供插入时显示这个回退内容。
-Suppose we have a component with the following template:
+假定 `my-component` 组件有下面模板:
``` html
This is my component!
- This will only be displayed if there is no content
- to be distributed.
+ 如果没有分发内容则显示我。
```
-Parent markup that uses the component:
+父组件模板:
``` html
@@ -610,7 +607,7 @@ Parent markup that uses the component:
```
-The rendered result will be:
+渲染结果:
``` html
@@ -620,13 +617,13 @@ The rendered result will be:
```
-### Named Slots
+### 具名 Slot
-`` elements have a special attribute, `name`, which can be used to further customize how content should be distributed. You can have multiple slots with different names. A named slot will match any element that has a corresponding `slot` attribute in the content fragment.
+`` 元素可以用一个特殊特性 `name` 配置如何分发内容。多个 slot 可以有不同的名字。具名 slot 将匹配内容片段中有对应 `slot` 特性的元素。
-There can still be one unnamed slot, which is the **default slot** that serves as a catch-all outlet for any unmatched content. If there is no default slot, unmatched content will be discarded.
+仍然可以有一个匿名 slot,它是**默认 slot**,作为找不到匹配的内容片段的回退插槽。如果没有默认的 slot,这些找不到匹配的内容片段将被抛弃。
-For example, suppose we have a `multi-insertion` component with the following template:
+例如,假定我们有一个 `multi-insertion` 组件,它的模板为:
``` html
@@ -636,7 +633,7 @@ For example, suppose we have a `multi-insertion` component with the following te
```
-Parent markup:
+父组件模板:
``` html
@@ -646,7 +643,7 @@ Parent markup:
```
-The rendered result will be:
+渲染结果为:
``` html
@@ -656,11 +653,11 @@ The rendered result will be:
```
-The content distribution API is a very useful mechanism when designing components that are meant to be composed together.
+在组合组件时,内容分发 API 是非常有用的机制。
-## Dynamic Components
+## 动态组件
-You can use the same mount point and dynamically switch between multiple components by using the reserved `` element and dynamically bind to its `is` attribute:
+多个组件可以使用同一个挂载点,然后动态地在它们之间切换。使用保留的 `` 元素,动态地绑定到它的 `is` 特性:
``` js
new Vue({
@@ -678,22 +675,22 @@ new Vue({
``` html
-
+
```
### `keep-alive`
-If you want to keep the switched-out components alive so that you can preserve its state or avoid re-rendering, you can add a `keep-alive` directive param:
+如果把切换出去的组件保留在内存中,可以保留它的状态或避免重新渲染。为此可以添加一个 `keep-alive` 指令参数:
``` html
-
+
```
-### `activate` Hook
+### `activate` 钩子
-When switching components, the incoming component might need to perform some asynchronous operation before it should be swapped in. To control the timing of component swapping, implement the `activate` hook on the incoming component:
+在切换组件时,切入组件在切入前可能需要进行一些异步操作。为了控制组件切换时长,给切入组件添加 `activate` 钩子:
``` js
Vue.component('activate-example', {
@@ -707,22 +704,22 @@ Vue.component('activate-example', {
})
```
-Note the `activate` hook is only respected during dynamic component swapping or the initial render for static components - it does not affect manual insertions with instance methods.
+注意 `activate` 钩子只作用于动态组件切换或静态组件初始化渲染的过程中,不作用于使用实例方法手工插入的过程中。
### `transition-mode`
-The `transition-mode` param attribute allows you to specify how the transition between two dynamic components should be executed.
+`transition-mode` 特性用于指定两个动态组件之间如何过渡。
-By default, the transitions for incoming and outgoing components happen simultaneously. This attribute allows you to configure two other modes:
+在默认情况下,进入与离开平滑地过渡。这个特性可以指定另外两种模式:
-- `in-out`: New component transitions in first, current component transitions out after incoming transition has finished.
+- `in-out`:新组件先过渡进入,等它的过渡完成之后当前组件过渡出去。
-- `out-in`: Current component transitions out first, new component transitions in after outgoing transition has finished.
+- `out-in`:当前组件先过渡出去,等它的过渡完成之后新组件过渡进入。
-**Example**
+**示例:**
``` html
-
+
{% endraw %}
-## Misc
-
-### Components and v-for
+## 杂项
-You can directly use `v-for` on the custom component, like any normal element:
+### 组件和 v-for
+自定义组件可以像普通元素一样直接使用 `v-for`:
``` html
```
-However, this won't pass any data to the component, because components have isolated scopes of their own. In order to pass the iterated data into the component, we should also use props:
+但是,不能传递数据给组件,因为组件的作用域是孤立的。为了传递数据给组件,应当使用 props:
``` html
```
-The reason for not automatically injecting `item` into the component is because that makes the component tightly coupled to how `v-for` works. Being explicit about where its data comes from makes the component reusable in other situations.
+不自动把 `item` 注入组件的原因是这会导致组件跟当前 `v-for` 紧密耦合。显式声明数据来自哪里可以让组件复用在其它地方。
-### Authoring Reusable Components
+### 编写可复用组件
-When authoring components, it is good to keep in mind whether you intend to reuse this component somewhere else later. It is OK for one-off components to have some tight coupling with each other, but reusable components should define a clean public interface.
+在编写组件时,记住是否要复用组件有好处。一次性组件跟其它组件紧密耦合没关系,但是可复用组件应当定义一个清晰的公开接口。
-The API for a Vue.js component essentially comes in three parts - props, events and slots:
+Vue.js 组件 API 来自三部分——prop,事件和 slot:
-- **Props** allow the external environment to feed data to the component;
+- **prop** 允许外部环境传递数据给组件;
-- **Events** allow the component to trigger actions in the external environment;
+- **事件** 允许组件触发外部环境的 action;
-- **Slots** allow the external environment to insert content into the component's view structure.
+- **slot** 允许外部环境插入内容到组件的视图结构内。
-With the dedicated shorthand syntax for `v-bind` and `v-on`, the intents can be clearly and succinctly conveyed in the template:
+使用 `v-bind` 和 `v-on` 的简写语法,模板的缩进清楚且简洁:
``` html
```
-### Async Components
+### 异步组件
-In large applications, we may need to divide the app into smaller chunks, and only load a component from the server when it is actually needed. To make that easier, Vue.js allows you to define your component as a factory function that asynchronously resolves your component definition. Vue.js will only trigger the factory function when the component actually needs to be rendered, and will cache the result for future re-renders. For example:
+在大型应用中,我们可能需要将应用拆分为小块,只在需要时才从服务器下载。为了让事情更简单,Vue.js 允许将组件定义为一个工厂函数,动态地解析组件的定义。Vue.js 只在组件需要渲染时触发工厂函数,并且把结果缓存起来,用于后面的再次渲染。例如:
``` js
Vue.component('async-example', function (resolve, reject) {
@@ -837,37 +833,37 @@ Vue.component('async-example', function (resolve, reject) {
})
```
-The factory function receives a `resolve` callback, which should be called when you have retrieved your component definition from the server. You can also call `reject(reason)` to indicate the load has failed. The `setTimeout` here is simply for demonstration; How to retrieve the component is entirely up to you. One recommended approach is to use async components together with [Webpack's code-splitting feature](http://webpack.github.io/docs/code-splitting.html):
+工厂函数接收一个 `resolve` 回调,在收到从服务器下载的组件定义时调用。也可以调用 `reject(reason)` 指示加载失败。这里 `setTimeout` 只是为了演示。怎么获取组件完全由你决定。推荐配合使用 [Webpack 的代码分割功能](http://webpack.github.io/docs/code-splitting.html):
``` js
Vue.component('async-webpack-example', function (resolve) {
- // this special require syntax will instruct webpack to
- // automatically split your built code into bundles which
- // are automatically loaded over ajax requests.
+ // 这个特殊的 require 语法告诉 webpack
+ // 自动将编译后的代码分割成不同的块,
+ // 这些块将通过 ajax 请求自动下载。
require(['./my-async-component'], resolve)
})
```
-### Assets Naming Convention
+### 资源命名约定
-Some assets, such as components and directives, appear in templates in the form of HTML attributes or HTML custom tags. Since HTML attribute names and tag names are **case-insensitive**, we often need to name our assets using kebab-case instead of camelCase, which can be a bit inconvenient.
+一些资源,如组件和指令,是以 HTML 特性或 HTML 自定义元素的形式出现在模板中。因为 HTML 特性的名字和标签的名字**不区分大小写**,所以资源的名字通常需使用 kebab-case 而不是 camelCase 的形式,这不大方便。
-Vue.js actually supports naming your assets using camelCase or PascalCase, and automatically resolves them as kebab-case in templates (similar to the name conversion for props):
+Vue.js 支持资源的名字使用 camelCase 或 PascalCase 的形式,并且在模板中自动将它们转为 kebab-case(类似于 prop 的命名约定):
``` js
-// in a component definition
+// 在组件定义中
components: {
- // register using camelCase
+ // 使用 camelCase 形式注册
myComponent: { /*... */ }
}
```
``` html
-
+
```
-This works nicely with [ES6 object literal shorthand](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#New_notations_in_ECMAScript_6):
+[ES6 对象字面量缩写](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#New_notations_in_ECMAScript_6) 也没问题:
``` js
// PascalCase
@@ -876,42 +872,42 @@ import DropdownMenu from './components/dropdown-menu';
export default {
components: {
- // use in templates as and
+ // 在模板中写作 和
TextBox,
DropdownMenu
}
}
```
-### Recursive Component
+### 递归组件
-Components can recursively invoke itself in its own template, however, it can only do so when it has the `name` option:
+组件在它的模板内可以递归地调用自己,不过,只有当它有 `name` 选项时才可以:
``` js
var StackOverflow = Vue.extend({
name: 'stack-overflow',
template:
'
'
})
```
-A component like the above will result in a "max stack size exceeded" error, so make sure recursive invocation is conditional. When you register a component globally using `Vue.component()`, the global ID is automatically set as the component's `name` option.
+上面组件会导致一个错误 "max stack size exceeded",所以要确保递归调用有终止条件。当使用 `Vue.component()` 全局注册一个组件时,组件 ID 自动设置为组件的 `name` 选项。
-### Fragment Instance
+### 片断实例
-When you use the `template` option, the content of the template will replace the element the Vue instance is mounted on. It is therefore recommended to always have a single root-level, plain element in templates.
+在使用 `template` 选项时,模板的内容将替换实例的挂载元素。因而推荐模板的顶级元素始终是单个元素。
-Instead of templates like this:
+不这么写模板:
``` html
root node 1
root node 2
```
-Prefer this:
+推荐这么写:
``` html
@@ -921,34 +917,34 @@ Prefer this:
```
-There are multiple conditions that will turn a Vue instance into a **fragment instance**:
+下面几种情况会让实例变成一个**片断实例**:
-1. Template contains multiple top-level elements.
-2. Template contains only plain text.
-3. Template contains only another component (which can potentially be a fragment instance itself).
-4. Template contains only an element directive, e.g. `` or vue-router's ``.
-5. Template root node has a flow-control directive, e.g. `v-if` or `v-for`.
+1. 模板包含多个顶级元素。
+2. 模板只包含普通文本。
+3. 模板只包含其它组件(其它组件可能是一个片段实例)。
+4. 模板只包含一个元素指令,如 `` 或 vue-router 的 ``。
+5. 模板根节点有一个流程控制指令,如 `v-if` 或 `v-for`。
-The reason is that all of the above cause the instance to have an unknown number of top-level elements, so it has to manage its DOM content as a fragment. A fragment instance will still render the content correctly. However, it will **not** have a root node, and its `$el` will point to an "anchor node", which is an empty Text node (or a Comment node in debug mode).
+这些情况让实例有未知数量的顶级元素,它将把它的 DOM 内容当作片断。片断实例仍然会正确地渲染内容。不过,它**没有**一个根节点,它的 `$el` 指向一个锚节点,即一个空的文本节点(在开发模式下是一个注释节点)。
-What's more important though, is that **non-flow-control directives, non-prop attributes and transitions on the component element will be ignored**, because there is no root element to bind them to:
+但是更重要的是,**组件元素上的非流程控制指令,非 prop 特性和过渡将被忽略**,因为没有根元素供绑定:
``` html
-
+
-
+
-
+
```
-There are, of course, valid use cases for fragment instances, but it is in general a good idea to give your component template a single, plain root element. It ensures directives and attributes on the component element to be properly transferred, and also results in slightly better performance.
+当然片断实例有它的用处,不过通常给组件一个根节点比较好。它会保证组件元素上的指令和特性能正确地转换,同时性能也稍微好些。
-### Inline Template
+### 内联模板
-When the `inline-template` special attribute is present on a child component, the component will use its inner content as its template, rather than treating it as distributed content. This allows more flexible template-authoring.
+如果子组件有 `inline-template` 特性,组件将把它的内容当作它的模板,而不是把它当作分发内容。这让模板更灵活。
``` html
@@ -957,4 +953,4 @@ When the `inline-template` special attribute is present on a child component, th
```
-However, `inline-template` makes the scope of your templates harder to reason about, and makes the component's template compilation un-cachable. As a best practice, prefer defining templates inside the component using the `template` option.
+但是 `inline-template` 让模板的作用域难以理解,并且不能缓存模板编译结果。最佳实践是使用 `template` 选项在组件内定义模板。
diff --git a/src/guide/computed.md b/src/guide/computed.md
index 348a7735d..c9144ea18 100644
--- a/src/guide/computed.md
+++ b/src/guide/computed.md
@@ -1,12 +1,12 @@
---
-title: Computed Properties
+title: 计算属性
type: guide
order: 5
---
-In-template expressions are very convenient, but they are really meant for simple operations only. Templates are meant to describe the structure of your view. Putting too much logic into your templates can make them bloated and hard to maintain. This is why Vue.js limits binding expressions to one expression only. For any logic that requires more than one expression, you should use a **computed property**.
+在模板中绑定表达式是非常便利的,但是它们实际上只用于简单的操作。模板是为了描述视图的结构。在模板中放入太多的逻辑会让模板过重且难以维护。这就是为什么 Vue.js 将绑定表达式限制为一个表达式。如果需要多于一个表达式的逻辑,应当使用**计算属性**。
-### Basic Example
+### 基础例子
``` html
@@ -21,16 +21,16 @@ var vm = new Vue({
a: 1
},
computed: {
- // a computed getter
+ // 一个计算属性的 getter
b: function () {
- // `this` points to the vm instance
+ // `this` 指向 vm 实例
return this.a + 1
}
}
})
```
-Result:
+结果:
{% raw %}
@@ -51,7 +51,7 @@ var vm = new Vue({
{% endraw %}
-Here we have declared a computed property `b`. The function we provided will be used as the getter function for the property `vm.b`:
+这里我们声明了一个计算属性 `b`。我们提供的函数将用作属性 `vm.b`的 getter。
``` js
console.log(vm.b) // -> 2
@@ -59,13 +59,13 @@ vm.a = 2
console.log(vm.b) // -> 3
```
-You can open the console and play with the example vm yourself. The value of `vm.b` is always dependent on the value of `vm.a`.
+你可以打开浏览器的控制台,修改 vm。`vm.b` 的值始终取决于 `vm.a` 的值。
-You can data-bind to computed properties in templates just like a normal property. Vue is aware that `vm.b` depends on `vm.a`, so it will update any bindings that depends on `vm.b` when `vm.a` changes. And the best part is that we've created this dependency relationship declaratively: the computed getter function is pure and has no side effects, which makes it easy to test and reason about.
+你可以像绑定普通属性一样在模板中绑定计算属性。Vue 知道 `vm.b` 依赖于 `vm.a`,因此当 `vm.a` 发生改变时,依赖于 `vm.b` 的绑定也会更新。而且最妙的是我们是声明式地创建这种依赖关系:计算属性的 getter 是干净无副作用的,因此也是易于测试和理解的。
-### Computed Property vs. $watch
+### 计算属性 vs. $watch
-Vue.js does provide an API method called `$watch` that allows you to observe data changes on a Vue instance. When you have some data that needs to change based on some other data, it is tempting to use `$watch` - especially if you are coming from an AngularJS background. However, it is often a better idea to use a computed property rather than an imperative `$watch` callback. Consider this example:
+Vue.js 提供了一个方法 `$watch`,它用于观察 Vue 实例上的数据变动。当一些数据需要根据其它数据变化时, `$watch` 很诱人 —— 特别是如果你来自 AngularJS。不过,通常更好的办法是使用计算属性而不是一个命令式的 `$watch` 回调。考虑下面例子:
``` html
{{fullName}}
@@ -89,7 +89,7 @@ vm.$watch('lastName', function (val) {
})
```
-The above code is imperative and repetitive. Compare it with a computed property version:
+上面代码是命令式的重复的。跟计算属性对比:
``` js
var vm = new Vue({
@@ -105,11 +105,11 @@ var vm = new Vue({
})
```
-Much better, isn't it?
+这样更好,不是吗?
-### Computed Setter
+### 计算 setter
-Computed properties are by default getter-only, but you can also provide a setter when you need it:
+计算属性默认只是 getter,不过在需要时你也可以提供一个 setter:
``` js
// ...
@@ -130,6 +130,6 @@ computed: {
// ...
```
-Now when you call `vm.fullName = 'John Doe'`, the setter will be invoked and `vm.firstName` and `vm.lastName` will be updated accordingly.
+现在在调用 `vm.fullName = 'John Doe'` 时,setter 会被调用,`vm.firstName` 和 `vm.lastName` 也会有相应更新。
-The technical details behind how computed properties are updated are [discussed in another section](reactivity.html#Inside-Computed-Properties) dedicated to the reactivity system.
+关于计算属性背后的原理和技术细节详见[计算属性的奥秘](reactivity.html#计算属性的奥秘)。
diff --git a/src/guide/conditional.md b/src/guide/conditional.md
index 5eecb72f4..b1c5c2390 100644
--- a/src/guide/conditional.md
+++ b/src/guide/conditional.md
@@ -1,36 +1,36 @@
---
-title: Conditional Rendering
+title: 条件渲染
type: guide
order: 7
---
## v-if
-In string templates, for example Handlebars, we would write a conditional block like this:
+在字符串模板中,如 Handlebars,我们得像这样写一个条件块:
``` html
-
+
{{#if ok}}
Yes
{{/if}}
```
-In Vue.js, we use the `v-if` directive to achieve the same:
+在 Vue.js,我们使用 `v-if` 指令实现同样的功能:
``` html
Yes
```
-It is also possible to add an "else" block with `v-else`:
+也可以用 `v-else` 添加一个 "else" 块:
``` html
Yes
No
```
-## Template v-if
+## template v-if
-Because `v-if` is a directive, it has to be attached to a single element. But what if we want to toggle more than one element? In this case we can use `v-if` on a `` element, which serves as an invisible wrapper. The final rendered result will not include the `` element.
+因为 `v-if` 是一个指令,需要将它添加到一个元素上。但是如果我们想切换多个元素呢?此时我们可以把一个 `` 元素当做包装元素,并在上面使用 `v-if`,最终的渲染结果不会包含它。
``` html
@@ -42,19 +42,19 @@ Because `v-if` is a directive, it has to be attached to a single element. But wh
## v-show
-Another option for conditionally displaying an element is the `v-show` directive. The usage is largely the same:
+另一个根据条件展示元素的选项是 `v-show` 指令。用法大体上一样:
``` html
Hello!
```
-The difference is that an element with `v-show` will always be rendered and remain in the DOM; `v-show` simply toggles the `display` CSS property of the element.
+不同的是有 `v-show` 的元素会始终渲染并保持在 DOM 中。`v-show` 是简单的切换元素的 CSS 属性 `display`。
-Note that `v-show` doesn't support the `` syntax.
+注意 `v-show` 不支持 `` 语法。
## v-else
-You can use the `v-else` directive to indicate an "else block" for `v-if` or `v-show`:
+可以用 `v-else` 指令给 `v-if` 或 `v-show` 添加一个 "else 块":
``` html
@@ -65,33 +65,33 @@ You can use the `v-else` directive to indicate an "else block" for `v-if` or `v-
```
-The `v-else` element must immediately follow the `v-if` or `v-show` element - otherwise it will not be recognized.
+`v-else` 元素必须立即跟在 `v-if` 或 `v-show` 元素的后面——否则它不能被识别。
-### Component caveat
+### 组件警告
-When used with components and `v-show`, `v-else` doesn't get applied properly due to directives priorities. So instead of doing this:
+将 `v-show` 用在组件上时,因为指令的优先级 `v-else` 会出现问题。因此不要这样做:
```html
-
This could be a component too
+
这可能也是一个组件
```
-Replace the `v-else` with another `v-show`:
+用另一个 `v-show` 替换 `v-else`:
```html
-
This could be a component too
+
这可能也是一个组件
```
-It does work as intended with `v-if`.
+这样就可以达到 `v-if` 的效果。
## v-if vs. v-show
-When a `v-if` block is toggled, Vue.js will have to perform a partial compilation/teardown process, because the template content inside `v-if` can also contain data bindings or child components. `v-if` is "real" conditional rendering because it ensures that event listeners and child components inside the conditional block are properly destroyed and re-created during toggles.
+在切换 `v-if` 块时,Vue.js 有一个局部编译/卸载过程,因为 `v-if` 之中的模板也可能包括数据绑定或子组件。`v-if` 是真实的条件渲染,因为它会确保条件块在切换当中合适地销毁与重建条件块内的事件监听器和子组件。
-`v-if` is also **lazy**: if the condition is false on initial render, it will not do anything - partial compilation won't start until the condition becomes true for the first time (and the compilation is subsequently cached).
+`v-if` 也是**惰性的**:如果在初始渲染时条件为假,则什么也不做——在条件第一次变为真时才开始局部编译(编译会被缓存起来)。
-In comparison, `v-show` is much simpler - the element is always compiled and preserved, with just simple CSS-based toggling.
+相比之下,`v-show` 简单得多——元素始终被编译并保留,只是简单地基于 CSS 切换。
-Generally speaking, `v-if` has higher toggle costs while `v-show` has higher initial render costs. So prefer `v-show` if you need to toggle something very often, and prefer `v-if` if the condition is unlikely to change at runtime.
+一般来说,`v-if` 有更高的切换消耗而 `v-show` 有更高的初始渲染消耗。因此,如果需要频繁切换 `v-show` 较好,如果在运行时条件不大可能改变 `v-if` 较好。
diff --git a/src/guide/custom-directive.md b/src/guide/custom-directive.md
index 850849d3f..835725179 100644
--- a/src/guide/custom-directive.md
+++ b/src/guide/custom-directive.md
@@ -1,75 +1,73 @@
---
-title: Custom Directives
+title: 自定义指令
type: guide
order: 14
---
-## Basics
+## 基础
-In addition to the default set of directives shipped in core, Vue.js also allows you to register custom directives. Custom directives provide a mechanism for mapping data changes to arbitrary DOM behavior.
+除了内置指令,Vue.js 也允许注册自定义指令。自定义指令提供一种机制将数据的变化映射为 DOM 行为。
-You can register a global custom directive with the `Vue.directive(id, definition)` method, passing in a **directive id** followed by a **definition object**. You can also register a local custom directive by including it in a component's `directives` option.
+可以用 `Vue.directive(id, definition)` 方法注册一个全局自定义指令,它接收两个参数**指令 ID** 与**定义对象**。也可以用组件的 `directives` 选项注册一个局部自定义指令。
-### Hook Functions
+### 钩子函数
-A definition object can provide several hook functions (all optional):
+定义对象可以提供几个钩子函数(都是可选的):
-- **bind**: called only once, when the directive is first bound to the element.
+- **bind**:只调用一次,在指令第一次绑定到元素上时调用。
-- **update**: called for the first time immediately after `bind` with the initial value, then again whenever the binding value changes. The new value and the previous value are provided as the argument.
+- **update**: 在 `bind` 之后立即以初始值为参数第一次调用,之后每当绑定值变化时调用,参数为新值与旧值。
-- **unbind**: called only once, when the directive is unbound from the element.
+- **unbind**:只调用一次,在指令从元素上解绑时调用。
-**Example**
+**示例**
``` js
Vue.directive('my-directive', {
bind: function () {
- // do preparation work
- // e.g. add event listeners or expensive stuff
- // that needs to be run only once
+ // 准备工作
+ // 例如,添加事件处理器或只需要运行一次的高耗任务
},
update: function (newValue, oldValue) {
- // do something based on the updated value
- // this will also be called for the initial value
+ // 值更新时的工作
+ // 也会以初始值为参数调用一次
},
unbind: function () {
- // do clean up work
- // e.g. remove event listeners added in bind()
+ // 清理工作
+ // 例如,删除 bind() 添加的事件监听器
}
})
```
-Once registered, you can use it in Vue.js templates like this (remember to add the `v-` prefix):
+在注册之后,便可以在 Vue.js 模板中这样用(记着添加前缀 `v-`):
``` html
```
-When you only need the `update` function, you can pass in a single function instead of the definition object:
+当只需要 `update` 函数时,可以传入一个函数替代定义对象:
``` js
Vue.directive('my-directive', function (value) {
- // this function will be used as update()
+ // 这个函数用作 update()
})
```
-### Directive Instance Properties
+### 指令实例属性
-All the hook functions will be copied into the actual **directive object**, which you can access inside these functions as their `this` context. The directive object exposes some useful properties:
+所有的钩子函数将被复制到实际的**指令对象**中,钩子内 `this` 指向这个指令对象。这个对象暴露了一些有用的属性:
-- **el**: the element the directive is bound to.
-- **vm**: the context ViewModel that owns this directive.
-- **expression**: the expression of the binding, excluding arguments and filters.
-- **arg**: the argument, if present.
-- **name**: the name of the directive, without the prefix.
-- **modifiers**: an object containing modifiers, if any.
-- **descriptor**: an object that contains the parsing result of the entire directive.
-- **params**: an object containing param attributes. [Explained below](#params).
+- **el**: 指令绑定的元素。
+- **vm**: 拥有该指令的上下文 ViewModel。
+- **expression**: 指令的表达式,不包括参数和过滤器。
+- **arg**: 指令的参数。
+- **name**: 指令的名字,不包含前缀。
+- **modifiers**: 一个对象,包含指令的修饰符。
+- **descriptor**: 一个对象,包含指令的解析结果。
-
You should treat all these properties as read-only and never modify them. You can attach custom properties to the directive object too, but be careful not to accidentally overwrite existing internal ones.
-An example of a custom directive using some of these properties:
+示例:
``` html
@@ -97,7 +95,7 @@ var demo = new Vue({
})
```
-**Result**
+**结果**
-### Object Literals
+### 对象字面量
-If your directive needs multiple values, you can also pass in a JavaScript object literal. Remember, directives can take any valid JavaScript expression:
+如果指令需要多个值,可以传入一个 JavaScript 对象字面量。记住,指令可以使用任意合法的 JavaScript 表达式:
``` html
@@ -137,9 +135,9 @@ Vue.directive('demo', function (value) {
})
```
-### Literal Modifier
+### 字面修饰符
-When a directive is used with the literal modifier, its attribute value will be interpreted as a plain string and passed directly into the `update` method. The `update` method will also be called only once, because a plain string cannot be reactive.
+当指令使用了字面修饰符,它的值将按普通字符串处理并传递给 `update` 方法。`update` 方法将只调用一次,因为普通字符串不能响应数据变化。
``` html
@@ -150,40 +148,40 @@ Vue.directive('demo', function (value) {
})
```
-### Element Directives
+### 元素指令
-In some cases, we may want our directive to be used in the form of a custom element rather than as an attribute. This is very similar to Angular's notion of "E" mode directives. Element directives provide a lighter-weight alternative to full-blown components (which are explained later in the guide). You can register a custom element directive like so:
+有时我们想以自定义元素的形式使用指令,而不是以特性的形式。这与 Angular 的 “E” 指令非常相似。元素指令可以看做是一个轻量组件。可以像下面这样注册一个自定义元素指令:
``` js
Vue.elementDirective('my-directive', {
- // same API as normal directives
+ // API 同普通指令
bind: function () {
- // manipulate this.el...
+ // 操作 this.el...
}
})
```
-Then, instead of:
+不这样写:
``` html
```
-We can write:
+这样写:
``` html
```
-Element directives cannot accept arguments or expressions, but it can read the element's attributes to determine its behavior.
+元素指令不能接受参数或表达式,但是它可以读取元素的特性从而决定它的行为。
-A big difference from normal directives is that element directives are **terminal**, which means once Vue encounters an element directive, it will completely skip that element - only the element directive itself will be able to manipulate that element and its children.
+迥异于普通指令,元素指令是**终结性**的,这意味着,一旦 Vue 遇到一个元素指令,它将跳过该元素及其子元素——只有该元素指令本身可以操作该元素及其子元素。
-## Advanced Options
+## 高级选项
### params
-Custom directive can provide a `params` array, and the Vue compiler will automatically extract these attributes on the element that the directive is bound to. Example:
+自定义指令可以接收一个 `params` 数组,指定一个特性列表,Vue 编译器将自动提取绑定元素的这些特性。例如:
``` html
@@ -197,7 +195,7 @@ Vue.directive('example', {
})
```
-This API also supports dynamic attributes. The `this.params[key]` value is automatically kept up-to-date. In addition, you can specify a callback when the value has changed:
+此 API 也支持动态属性。`this.params[key]` 会自动保持更新。另外,可以指定一个回调,在值变化时调用:
``` html
@@ -213,11 +211,11 @@ Vue.directive('example', {
})
```
-
Note that similar to props, directive params follow the same camelCase <=> kebab case mapping between JavaScript and HTML. For example, for a param used as `disable-effect` in the template, you need to access it as `disableEffect` in JavaScript.
### deep
-If your custom directive is expected to be used on an Object, and it needs to trigger `update` when a nested property inside the object changes, you need to pass in `deep: true` in your directive definition.
+如果自定义指令用在一个对象上,当对象内部属性变化时要触发 `update`,则在指令定义对象中指定 `deep: true`。
``` html
@@ -227,25 +225,23 @@ If your custom directive is expected to be used on an Object, and it needs to tr
Vue.directive('my-directive', {
deep: true,
update: function (obj) {
- // will be called when nested properties in `obj`
- // changes.
+ // 在 `obj` 的嵌套属性变化时调用
}
})
```
### twoWay
-If your directive expects to write data back to the Vue instance, you need to pass in `twoWay: true`. This option allows the use of `this.set(value)` inside the directive:
+如果指令想向 Vue 实例写回数据,则在指令定义对象中指定 `twoWay: true` 。该选项允许在指令中使用 `this.set(value)`:
``` js
Vue.directive('example', {
twoWay: true,
bind: function () {
this.handler = function () {
- // set data back to the vm.
- // If the directive is bound as v-example="a.b.c",
- // this will attempt to set `vm.a.b.c` with the
- // given value.
+ // 将数据写回 vm
+ // 如果指令这样绑定 v-example="a.b.c"
+ // 它将用给定值设置 `vm.a.b.c`
this.set(this.el.value)
}.bind(this)
this.el.addEventListener('input', this.handler)
@@ -258,7 +254,7 @@ Vue.directive('example', {
### acceptStatement
-Passing in `acceptStatement:true` enables your custom directive to accept inline statements like `v-on` does:
+传入 `acceptStatement:true` 可以让自定义指令接受内联语句,就像 `v-on` 那样:
``` html
@@ -268,22 +264,21 @@ Passing in `acceptStatement:true` enables your custom directive to accept inline
Vue.directive('my-directive', {
acceptStatement: true,
update: function (fn) {
- // the passed in value is a function which when called,
- // will execute the "a++" statement in the owner vm's
- // scope.
+ // 传入值是一个函数
+ // 在调用它时将在所属实例作用域内计算 "a++" 语句
}
})
```
-Use this wisely though, because in general you want to avoid side-effects in your templates.
+明智地使用,因为通常你要在模板中避免副效应。
### terminal
> 1.0.19+
-Vue compiles templates by recursively walking the DOM tree. However when it encounters a **terminal** directive, it will stop walking that element's children. The terminal directive takes over the job of compiling the element and its children. For example, `v-if` and `v-for` are both terminal directives.
+Vue 通过递归遍历 DOM 树来编译模块。但是当它遇到 **terminal** 指令时会停止遍历这个元素的后代元素。这个指令将接管编译这个元素及其后代元素的任务。`v-if` 和 `v-for` 都是 terminal 指令。
-Writing a custom terminal directive is an advanced topic and requires decent knowledge of Vue's compilation pipeline, but it's possible. You can specify a custom terminal directive by specifying `terminal: true`. You will also likely need to use `Vue.FragmentFactory` for partial compilation. Here's an example of a custom terminal directive that compiles and "injects" its content template to another location on the page:
+编写自定义 terminal 指令是一个高级话题,需要较好的理解 Vue 的编译流程,但这不是说不可能编写自定义 terminal 指令。用 `terminal: true` 指定自定义 terminal 指令,可能还需要用 `Vue.FragmentFactory` 来编译 partial。下面是一个自定义 terminal 指令,它编译它的内容模板并将结果注入到页面的另一个地方:
``` js
var FragmentFactory = Vue.FragmentFactory
@@ -318,10 +313,10 @@ Vue.directive('inject', {
```
-If you want to write a custom terminal directive, it is recommend that you read through the source code of built-in terminal directives like `v-if` and `v-for` to get a better understanding of Vue internals.
+如果你想编写自定义 terminal 指令,建议你通读内置 terminal 指令的源码,如 `v-if` 和 `v-for`,以便更好地了解 Vue 的内部机制。
### priority
-You can optionally provide a priority number for your directive. If no priority is specified, a default priority will be used - `1000` for normal directives and `2000` for terminal directives. A directive with a higher priority will be processed earlier than other directives on the same element. Directives with the same priority will be processed in the order they appear in the element's attribute list, although that order is not guaranteed to be consistent in different browsers.
+可以给指令指定一个优先级。如果没有指定,普通指令默认是 `1000`, terminal 指令默认是 `2000`。同一个元素上优先级高的指令会比其它指令处理得早一些。优先级一样的指令按照它在元素特性列表中出现的顺序依次处理,但是不能保证这个顺序在不同的浏览器中是一致的。
-You can checkout the priorities for some built-in directives in the [API reference](/api/#Directives). Additionally, flow control directives `v-if` and `v-for` always have the highest priority in the compilation process.
+可以在 [API](/api/#指令) 中查看内置指令的优先级。另外,流程控制指令 `v-if` 和 `v-for` 在编译过程中始终拥有最高的优先级。
diff --git a/src/guide/custom-filter.md b/src/guide/custom-filter.md
index da50a142c..c7761f9a4 100644
--- a/src/guide/custom-filter.md
+++ b/src/guide/custom-filter.md
@@ -1,12 +1,12 @@
---
-title: Custom Filters
+title: 自定义过滤器
type: guide
order: 15
---
-## Basics
+## 基础
-Similar to custom directives, you can register a custom filter with the global `Vue.filter()` method, passing in a **filterID** and a **filter function**. The filter function takes a value as the argument and returns the transformed value:
+类似于自定义指令,可以用全局方法 `Vue.filter()` 注册一个自定义过滤器,它接收两个参数:**过滤器 ID** 和**过滤器函数**。过滤器函数以值为参数,返回转换后的值:
``` js
Vue.filter('reverse', function (value) {
@@ -19,7 +19,7 @@ Vue.filter('reverse', function (value) {
```
-The filter function also receives any inline arguments:
+过滤器函数可以接收任意数量的参数:
``` js
Vue.filter('wrap', function (value, begin, end) {
@@ -32,19 +32,19 @@ Vue.filter('wrap', function (value, begin, end) {
```
-## Two-way Filters
+## 双向过滤器
-Up till now we have used filters to transform values coming from the model and before displaying them in the view. But it is also possible to define a filter that transforms the value before it is written back to the model from the view (input elements):
+目前我们使用过滤器都是在把来自模型的值显示在视图之前转换它。不过也可以定义一个过滤器,在把来自视图(`` 元素)的值写回模型之前转化它:
``` js
Vue.filter('currencyDisplay', {
// model -> view
- // formats the value when updating the input element.
+ // 在更新 `` 元素之前格式化值
read: function(val) {
return '$'+val.toFixed(2)
},
// view -> model
- // formats the value when writing to the data.
+ // 在写回数据之前格式化值
write: function(val, oldVal) {
var number = +val.replace(/[^\d.]/g, '')
return isNaN(number) ? 0 : parseFloat(number.toFixed(2))
@@ -52,7 +52,7 @@ Vue.filter('currencyDisplay', {
})
```
-Demo:
+示例:
{% raw %}
@@ -80,9 +80,9 @@ new Vue({
{% endraw %}
-## Dynamic Arguments
+## 动态参数
-If a filter argument is not enclosed by quotes, it will be evaluated dynamically in the current vm's data context. In addition, the filter function is always invoked using the current vm as its `this` context. For example:
+如果过滤器参数没有用引号包起来,则它会在当前 vm 作用域内动态计算。另外,过滤器函数的 `this` 始终指向调用它的 vm。例如:
``` html
@@ -91,11 +91,11 @@ If a filter argument is not enclosed by quotes, it will be evaluated dynamically
``` js
Vue.filter('concat', function (value, input) {
- // here `input` === `this.userInput`
+ // `input` === `this.userInput`
return value + input
})
```
-For this simple example above, you can achieve the same result with just an expression, but for more complicated procedures that need more than one statement, you need to put them either in a computed property or a custom filter.
+上例比较简单,也可以用表达式达到相同的结果,但是对于更复杂的逻辑——需要多于一个语句,这时需要将它放到计算属性或自定义过滤器中。
-The built-in `filterBy` and `orderBy` filters are both filters that perform non-trivial work on the Array being passed in and relies on the current state of the owner Vue instance.
+内置过滤器 `filterBy` 和 `orderBy`,根据所属 Vue 实例的当前状态,过滤/排序传入的数组。
diff --git a/src/guide/events.md b/src/guide/events.md
index fd4bfe8d9..0197f3fa8 100644
--- a/src/guide/events.md
+++ b/src/guide/events.md
@@ -1,12 +1,12 @@
---
-title: Methods and Event Handling
+title: 方法与事件处理器
type: guide
order: 9
---
-## Method Handler
+## 方法处理器
-We can use the `v-on` directive to listen to DOM events:
+可以用 `v-on` 指令监听 DOM 事件:
``` html
@@ -14,7 +14,7 @@ We can use the `v-on` directive to listen to DOM events:
```
-We are binding a click event listener to a method named `greet`. Here's how to define that method in our Vue instance:
+我们绑定了一个单击事件处理器到一个方法 `greet`。下面在 Vue 实例中定义这个方法:
``` js
var vm = new Vue({
@@ -22,22 +22,22 @@ var vm = new Vue({
data: {
name: 'Vue.js'
},
- // define methods under the `methods` object
+ // 在 `methods` 对象中定义方法
methods: {
greet: function (event) {
- // `this` inside methods point to the Vue instance
+ // 方法内 `this` 指向 vm
alert('Hello ' + this.name + '!')
- // `event` is the native DOM event
+ // `event` 是原生 DOM 事件
alert(event.target.tagName)
}
}
})
-// you can invoke methods in JavaScript too
+// 也可以在 JavaScript 代码中调用方法
vm.greet() // -> 'Hello Vue.js!'
```
-Test it yourself:
+自己测试一下:
{% raw %}
@@ -49,12 +49,12 @@ var vm = new Vue({
data: {
name: 'Vue.js'
},
- // define methods under the `methods` object
+ // 在 `methods` 对象中定义方法
methods: {
greet: function (event) {
- // `this` inside methods point to the vm
+ // 方法内 `this` 指向 vm
alert('Hello ' + this.name + '!')
- // `event` is the native DOM event
+ // `event` 是原生 DOM 事件
alert(event.target.tagName)
}
}
@@ -62,9 +62,9 @@ var vm = new Vue({
{% endraw %}
-## Inline Statement Handler
+## 内联语句处理器
-Instead of binding directly to a method name, we can also use an inline JavaScript statement:
+除了直接绑定到一个方法,也可以用内联 JavaScript 语句:
``` html
@@ -101,9 +101,9 @@ new Vue({
{% endraw %}
-Similar to the restrictions on inline expressions, event handlers are restricted to **one statement only**.
+类似于内联表达式,事件处理器限制为**一个语句**。
-Sometimes we also need to access the original DOM event in an inline statement handler. You can pass it into a method using the special `$event` variable:
+有时也需要在内联语句处理器中访问原生 DOM 事件。可以用特殊变量 `$event` 把它传入方法:
``` html
@@ -113,63 +113,62 @@ Sometimes we also need to access the original DOM event in an inline statement h
// ...
methods: {
say: function (msg, event) {
- // now we have access to the native event
+ // 现在我们可以访问原生事件对象
event.preventDefault()
}
}
```
-## Event Modifiers
+## 事件修饰符
-It is a very common need to call `event.preventDefault()` or `event.stopPropagation()` inside event handlers. Although we can do this easily inside methods, it would be better if the methods can be purely about data logic rather than having to deal with DOM event details.
+在事件处理器中经常需要调用 `event.preventDefault()` 或 `event.stopPropagation()`。尽管我们在方法内可以轻松做到,不过让方法是纯粹的数据逻辑而不处理 DOM 事件细节会更好。
-To address this problem, Vue.js provides two **event modifiers** for `v-on`: `.prevent` and `.stop`. Recall that modifiers are directive postfixes denoted by a dot:
+为了解决这个问题,Vue.js 为 `v-on` 提供两个 **事件修饰符**:`.prevent` 与 `.stop`。你是否还记得修饰符是点号打头的指令后缀?
``` html
-
+
-
+
-
+
-
+
```
-In 1.0.16, two additional modifiers have been introduced:
+1.0.16 添加了两个额外的修饰符:
``` html
-
+