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

Walter White aka Heisenberg

``` -- **See also:** [Components](/guide/components.html) +- **另见:** [组件](/guide/components.html)

Vue.nextTick( callback )

-- **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)

Vue.component( id, [definition] )

-- **Arguments:** +- **参数:** - `{String} id` - `{Function | Object} [definition]` -- **Usage:** +- **用法:** - Register or retrieve a global component. + 注册或获取全局组件。 ``` js - // register an extended constructor - Vue.component('my-component', Vue.extend({ /* ... */ })) + // 注册组件,传入一个扩展的构造器 + Vue.component('my-component', Vue.extend({ /* ... */})) - // register an options object (automatically call Vue.extend) + // 注册组件,传入一个选项对象(自动调用 Vue.extend) Vue.component('my-component', { /* ... */ }) - // retrieve a registered component (always return constructor) + // 获取注册的组件(始终返回构造器) var MyComponent = Vue.component('my-component') ``` -- **See also:** [Components](/guide/components.html). +- **另见:** [组件](/guide/components.html)

Vue.transition( id, [hooks] )

-- **Arguments:** +- **参数:** - `{String} id` - `{Object} [hooks]` -- **Usage:** +- **用法:** - Register or retrieve a global transition hooks object. + 注册或获取全局的过渡钩子对象。 ``` js - // register + // 注册 Vue.transition('fade', { enter: function () {}, leave: function () {} }) - // retrieve registered hooks + // 获取注册的钩子 var fadeTransition = Vue.transition('fade') ``` -- **See also:** [Transitions](/guide/transitions.html). +- **另见:** [过渡](/guide/transitions.html)

Vue.partial( id, [partial] )

-- **Arguments:** +- **参数:** - `{String} id` - `{String} [partial]` -- **Usage:** +- **用法:** - Register or retrieve a global template partial string. + 注册或获取全局的 partial。 ``` js - // register + // 注册 Vue.partial('my-partial', '
Hi
') - // retrieve registered partial + // 获取注册的 partial var myPartial = Vue.partial('my-partial') ``` -- **See also:** [Special Elements - <partial>](#partial). +- **另见:** [特殊元素 - <partial>](#partial)

Vue.use( plugin, [options] )

-- **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 的状态。集中管理状态更易于理解状态将怎样变化。组件仍然可以拥有和管理它的私有状态。 -![State Management](/images/state.png) +![状态管理](/images/state.png) -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!

      +

      尽管可以用 Mustache 标签绑定 class,比如 `{% raw %}class="{{ className }}"{% endraw %}`,但是我们不推荐这种写法和 `v-bind:class` 混用。两者只能选其一!

      -### 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.

      +

      对于自定义标签名字,Vue.js 不强制要求遵循 [W3C 规则](http://www.w3.org/TR/custom-elements/#concepts)(小写,并且包含一个短杠),尽管遵循这个规则比较好。

      -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 ``, `