vue.js中英文api

vue

全局配置

   Vue.config is an object containing Vue’s global configurations. You can modify its properties listed below before bootstrapping your application:

Vue.config是包含Vue的全局配置的对象。在启动应用程序之前,可以修改下面列出的属性:

英文原文出自:https://vuejs" title="vuejs">vuejs.org/v2/api/#performance

 

silent

 

  • 类型: boolean
  • 默认值: false
  • 用法:

Vue.config.silent = true

  • Suppress all Vue logs and warnings. 禁止所有的Vue日志和警告。
  • Source

 

optionMergeStrategies

  • 类型: { [key: string]: Function }
  • 默认值: {}
  • 用法:
  • Define custom merging strategies for options.为选项定义定制的合并策略。
  • The merge strategy receives the value of that option defined on the parent and child instances as the first and second arguments, respectively. The context Vue instance is passed as the third argument.
  • 他的合并策略接收到父和子实例中定义的那个选项的值,分别作为第一个和第二个参数。上下文Vue实例作为第三个参数传递。
  • See also: Custom Option Merging Strategies
  • Source

Vue.config.optionMergeStrategies._my_option = function (parent, child, vm) {

  return child + 1

}

const Profile = Vue.extend({

  _my_option: 1

})

// Profile.options._my_option = 2

 

devtools

  • 类型: boolean
  • 默认值: true (false in production builds)
  • 用法:
  • Configure whether to allow 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.

// make sure to set this synchronously immediately after loading Vue

//确保在加载Vue后立即将此设置为同步。

Vue.config.devtools = true

 配置是否允许vue-devtools检查。该选项的默认值在开发构建中是true,在生产构建中是false。您可以将其设置为true以便对生产构建进行检查。

  • Source

errorHandler

  • 类型: Function
  • 默认值: undefined
  • 用法:

    • Assign a handler for uncaught errors during component render function and watchers. The handler gets called with the error and the Vue instance. 在组件渲染功能和观察者期间为未捕获的错误分配处理程序。处理程序被调用带有错误和Vue实例。
    • In 2.2.0+, this hook also captures errors in component lifecycle hooks. Also, when this hook is undefined, captured errors will be logged with console.error instead of crashing the app.

Vue.config.errorHandler = function (err, vm, info) {

  // handle error 处理错误

  // `info` is a Vue-specific error info, e.g. which lifecycle hook

 //“info”是Vue-specific的一个错误信息,例如哪个生命周期的挂钩

 // the error was found in. Only available in 2.2.0+

 //这个错误只在2.2.0+版本可用

}

在2.2.0+以上,此钩子还捕获组件生命周期钩子中的错误。此外,当此钩子未定义时,捕获的错误将使用console.error记录,而不是崩溃应用程序。

  • In 2.4.0+ this hook also captures errors thrown inside Vue custom event handlers.

 在2.4.0以上,此钩子还捕获Vue自定义事件处理程序中抛出的错误。

  • Sentry, an error tracking service, provides official integration using this option.

错误跟踪服务,使用此选项提供官方集成。

  • Source

warnHandler

New in 2.4.0+

  • 类型: Function
  • 默认值: undefined
  • 用法:

    • Assign a custom handler for runtime Vue warnings. Note this only works during development and is ignored in production.

Vue.config.warnHandler = function (msg, vm, trace) {

  // `trace` is the component hierarchy trace

 //’trace’是组件层级跟踪

}

为运行时Vue警告分配一个自定义处理程序。注意,这只能在开发过程中起作用,在生产中被忽略。

ignoredElements

  • 类型: Array<string>
  • 默认值: []
  • 用法:

    • Make Vue ignore custom elements defined outside of Vue (e.g., using the Web Components APIs). Otherwise, it will throw a warning about an Unknown custom element, assuming that you forgot to register a global component or misspelled a component name.

Vue.config.ignoredElements = [

  \'my-custom-web-component\', \'another-web-component\'

]

使Vue忽略Vue之外定义的元素(例如,使用Web Components API)。否则,将会发出关于“未知”自定义元素的警告,假设您忘记注册全局组件或拼写错误的组件名称。

  • Source

keyCodes

  • 类型: { [key: string]: number | Array<number> }
  • 默认值: {}
  • 用法:
  • Define custom key alias(es) for v-on.为v-on定义用户关键别名。
  • Source

Vue.config.keyCodes = {

  v: 86,

  f1: 112,

  // camelCase won`t work

  mediaPlayPause: 179,

  // instead you can use kebab-case with double quotation marks`

 //相反你可以使用双引号来使用kebab-case

  "media-play-pause": 179,

  up: [38, 87]

}

<input type="text" @keyup.media-play-pause="method">

performance

New in 2.2.0+

  • 类型: boolean
  • 默认值: false (from 2.2.3+)
  • 用法:

Set this to true to enable component init, compile, render and patch performance tracing in the browser devtool timeline. Only works in development mode and in browsers that support the performance.mark API. 将其设置为true以在浏览器devtool时间轴中启用组件初始化,编译,渲染和修补性能跟踪。只适用于开发模式和支持performance.mark API的浏览器。

productionTip

New in 2.2.0+

  • 类型: boolean
  • 默认值: true
  • 用法:

Set this to false to prevent the production tip on Vue startup.将其设置为false以防止Vue启动时的生产提示。

Global API

Vue.extend( options )

  • 参数:
  • {Object} options
  • 用法:

Create a “subclass” of the base Vue constructor. The argument should be an object containing component options. 创建基础Vue构造函数的“子类”。参数应该是包含组件选项的对象。

The special case to note here is the data option - it must be a function when used with Vue.extend().这里要注意的特殊情况是data选项——它必须是与vue.extend ()一起使用的函数。

<div id="mount-point"></div>

// create constructor

var Profile = Vue.extend({

  template: \'<p>{{firstName}} {{lastName}} aka {{alias}}</p>\',

  data: function () {

    return {

      firstName: \'Walter\',

      lastName: \'White\',

      alias: \'Heisenberg\'

    }

  }

})

// create an instance of Profile and mount it on an element

//创建一个概要文件实例并将其挂载到一个元素上

new Profile().$mount(\'#mount-point\')

Will result in:

<p>Walter White aka Heisenberg</p>

  • See also: Components
  • Source

Vue.nextTick( [callback, context] )

  • 参数:
  • {Function} [callback]
  • {Object} [context]
  • 用法:

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更新。

// modify data 修改数据

vm.msg = \'Hello\'

// DOM not updated yet DOM还未更新

Vue.nextTick(function () {

  // DOM updated DOM已更新

})

New in 2.1.0+: returns a Promise if no callback is provided and Promise is supported in the execution environment. Please note that Vue does not come with a Promise polyfill, so if you target browsers that don’t support Promises natively (looking at you, IE), you will have to provide a polyfill yourself.

2.1.0+中的新功能:如果不提供回调并在执行环境中支持Promise,则返回Promise。请注意,Vue不附带Promise polyfill,因此,如果您定位不支持Promise的浏览器(查看您,IE),则必须自己提供一个polyfill。

  • See also: Async Update Queue
  • Source

 

Vue.set( target, key, value )

  • Arguments:
  • {Object | Array} target
  • {string | number} key
  • {any} value
  • Returns: the set value.
  • 用法:

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.

在对象上设置属性。如果对象是反应的,请确保将该属性创建为无效属性并触发视图更新。这主要用于解决Vue无法检测属性添加的限制。

Note the object cannot be a Vue instance, or the root data object of a Vue instance.

注意对象不能是Vue实例,也不能是Vue实例的根数据对象。

  • See also: Reactivity in Depth
  • Source

Vue.delete( target, key )

  • Arguments:
  • {Object | Array} target
  • {string | number} key/index

Only in 2.2.0+: Also works with Array + index.

  • 用法:

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.

删除对象上的属性。如果对象是反应的,请确保删除触发视图更新。这主要用于解决Vue无法检测到属性删除的限制,但是您很少需要使用它。

The target object cannot be a Vue instance, or the root data object of a Vue instance.

目标对象不能是Vue实例,也不能是Vue实例的根数据对象。

  • See also: Reactivity in Depth
  • Source

Vue.directive( id, [definition] )

  • Arguments:
  • {string} id
  • {Function | Object} [definition]
  • 用法:

Register or retrieve a global directive. 注册或检索全局配置参数。

// register

Vue.directive(\'my-directive\', {

  bind: function () {},

  inserted: function () {},

  update: function () {},

  componentUpdated: function () {},

  unbind: function () {}

})

// register (function directive)

Vue.directive(\'my-directive\', function () {

  // this will be called as `bind` and `update`

})

// getter, return the directive definition if registered

var myDirective = Vue.directive(\'my-directive\')

  • See also: Custom Directives
  • Source

Vue.filter( id, [definition] )

  • Arguments:
  • {string} id
  • {Function} [definition]
  • 用法:

Register or retrieve a global filter. 注册或检索全局过滤器。

// register

Vue.filter(\'my-filter\', function (value) {

  // return processed value

})

// getter, return the filter if registered

var myFilter = Vue.filter(\'my-filter\')

  • Source

Vue.component( id, [definition] )

  • Arguments:
  • {string} id
  • {Function | Object} [definition]
  • 用法:

Register or retrieve a global component. Registration also automatically sets the component’s name with the given id.

注册或检索全局组件。注册还会自动设置组件的名称与给定的ID。

// register an extended constructor

Vue.component(\'my-component\', Vue.extend({ /* ... */ }))

// register an options object (automatically call Vue.extend)

Vue.component(\'my-component\', { /* ... */ })

// retrieve a registered component (always return constructor)

var MyComponent = Vue.component(\'my-component\')

  • See also: Components
  • Source

Vue.use( plugin )

  • Arguments:
  • {Object | Function} plugin
  • 用法:

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插件。如果插件是一个Object,它必须暴露一个安装方法。如果它是一个函数本身,它将被视为安装方法。将使用Vue作为参数调用安装方法。

When this method is called on the same plugin multiple times, the plugin will be installed only once.

当这个方法在同一个插件上多次调用时,插件只能安装一次。

  • See also: Plugins
  • Source

Vue.mixin( mixin )

  • Arguments:
  • {Object} mixin
  • 用法:

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.

在全局应用mixin,这会影响之后创建的每个Vue实例。插件作者可以使用这种方式将自定义行为注入到组件中。不推荐在应用程序代码。

  • See also: Global Mixin
  • Source

Vue.compile( template )

  • Arguments:
  • {string} template
  • 用法:

Compiles a template string into a render function. Only available in the full build.

将模板字符串编译成渲染函数。仅在完整版中可用。

var res = Vue.compile(\'<div><span>{{ msg }}</span></div>\')

new Vue({

  data: {

    msg: \'hello\'

  },

  render: res.render,

  staticRenderFns: res.staticRenderFns

})

  • See also: Render Functions
  • Source

Vue.version

  • 详情: Provides the installed version of Vue as a string. This is especially useful for community plugins and components, where you might use different strategies for different versions.

提供Vue的安装版本作为字符串。这对社区插件和组件特别有用,您可以在不同版本中使用不同的策略。

  • 用法:
  • Source

var version = Number(Vue.version.split(\'.\')[0])

if (version === 2) {

  // Vue v2.x.x

} else if (version === 1) {

  // Vue v1.x.x

} else {

  // Unsupported versions of Vue

}

Options / Data

data

  • 类型: Object | Function
  • 约束: Only accepts Function when used in a component definition.在组件定义中使用时,只接受Function。
  • 详情:

The data object for the Vue instance. Vue will recursively convert its properties into getter/setters to make it “reactive”. The object must be plain: native objects such as browser API objects and prototype properties are ignored. A rule of thumb is that data should just be data - it is not recommended to observe objects with their own stateful behavior.

Vue实例的数据对象。 Vue会将其属性递归转换成getter / setter,使其“反应”。该对象必须是简单的:本机对象(如浏览器API对象和原型属性)将被忽略。经验法则是数据应该是数据 - 不建议用自己的状态观察对象。

Once observed, you can no longer add reactive properties to the root data object. It is therefore recommended to declare all root-level reactive properties upfront, before creating the instance.

一旦观察到,您将无法再向根数据对象添加反应属性。因此,建议在创建实例之前先声明所有根级别的反应属性。

After 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, so vm.a will be equivalent to vm.$data.a.

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.

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 use a plain object for data, that same object will be shared by reference across all instances created! By providing a data function, every time a new instance is created we can call it to return a fresh copy of the initial data.

创建实例后,原始数据对象可以作为vm。$ data访问。 Vue实例还代理在数据对象上发现的所有属性,因此vm.a将等效于vm。$ data.a。

以_或$开头的属性将不会被Vue实例代理,因为它们可能与Vue的内部属性和API方法相冲突。你将不得不以vm。$ data._property的形式访问它们。

定义组件时,必须将数据声明为返回初始数据对象的函数,因为将使用相同定义创建许多实例。如果我们对数据使用一个简单的对象,那么同一个对象将被所有创建的实例的引用共享。通过提供数据功能,每次创建新实例时,我们可以调用它来返回初始数据的新副本。

If required, a deep clone of the original object can be obtained by passing vm.$datathrough JSON.parse(JSON.stringify(...)).

如果需要,可以通过传递vm。$ datathrough JSON.parse(JSON.stringify(...))获得原始对象的深层克隆。

  • 例子:

    • Note that you should not use an arrow function with the data property (e.g. data: () => { return { a: this.myProp }}). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.myProp will be undefined.
    • 请注意,您不应使用数据属性的箭头函数(例如数据:()=> {return {a:this.myProp}})。原因是箭头函数绑定父上下文,所以这不会是你期望的Vue实例,而this.myProp将是未定义的。
    • See also: Reactivity in Depth
    • Source

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

var Component = Vue.extend({

  data: function () {

    return { a: 1 }

  }

})

 

 

props

  • 类型: Array<string> | Object
  • 详情:

A list/hash of attributes that are exposed to accept data from the parent component. It has an Array-based simple syntax and an alternative Object-based syntax that allows advanced configurations such as type checking, custom validation and default values.

暴露以接受来自父组件的数据的属性的列表/散列。它具有基于数组的简单语法和基于对象的替代语法,允许高级配置,如类型检查,自定义验证和默认值。

  • 例子:
  • See also: Props
  • Source

// simple syntax

Vue.component(\'props-demo-simple\', {

  props: [\'size\', \'myMessage\']

})

// object syntax with validation

Vue.component(\'props-demo-advanced\', {

  props: {

    // type check

    height: Number,

    // type check plus other validations

    age: {

      type: Number,

      default: 0,

      required: true,

      validator: function (value) {

        return value >= 0

      }

    }

  }

})

propsData

  • 类型: { [key: string]: any }
  • 约束: only respected in instance creation via new. 只有通过新创建的实例才能得到支持。
  • 详情:

Pass props to an instance during its creation. This is primarily intended to make unit testing easier.

在创建过程中将道具传递给实例。这主要是为了使单元测试更容易。

  • 例子:
  • Source

var Comp = Vue.extend({

  props: [\'msg\'],

  template: \'<div>{{ msg }}</div>\'

})

var vm = new Comp({

  propsData: {

    msg: \'hello\'

  }

})

computed

  • 类型: { [key: string]: Function | { get: Function, set: Function } }
  • 详情:

Computed properties to be mixed into the Vue instance. All getters and setters have their this context automatically bound to the Vue instance.

Note that you should not use an arrow function to define a computed property(e.g. aDouble: () => this.a * 2). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.awill be undefined.

要混合到Vue实例中的计算属性。所有getter和setter都将其上下文自动绑定到Vue实例。

请注意,您不应使用箭头函数来定义计算属性(例如aDouble:()=> this.a * 2)。原因是箭头函数绑定父上下文,所以这不会是你期望的Vue实例,而this.awill是未定义的。

Computed properties are cached, and only re-computed on reactive dependency changes. Note that if a certain dependency is out of the instance’s scope (i.e. not reactive), the computed property will not be updated.

计算的属性被缓存,并且仅在反应性依赖性更改上重新计算。请注意,如果某个依赖关系超出了实例的范围(即没有反应),则计算的属性将不会被更新。

  • 例子:
  • See also: Computed Properties
  • Source

var vm = new Vue({

  data: { a: 1 },

  computed: {

    // get only

    aDouble: function () {

      return this.a * 2

    },

    // both get and set

    aPlus: {

      get: function () {

        return this.a + 1

      },

      set: function (v) {

        this.a = v - 1

      }

    }

  }

})

vm.aPlus   // => 2

vm.aPlus = 3

vm.a       // => 2

vm.aDouble // => 4

methods

  • 类型: { [key: string]: Function }
  • 详情:

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 thiscontext automatically bound to the Vue instance.

Note that you should not use an arrow function to define a method (e.g. plus: () => this.a++). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.a will be undefined.

要混合到Vue实例中的方法。您可以直接在VM实例上访问这些方法,或者在指令表达式中使用它们。所有方法都将自己的此上下文绑定到Vue实例。

请注意,您不应该使用箭头函数来定义一个方法(例如加:()=> this.a ++)。原因是箭头函数绑定父上下文,所以这不会是你期望的Vue实例,而this.a将是未定义的。

  • 例子:
  • See also: Event Handling
  • Source

var vm = new Vue({

  data: { a: 1 },

  methods: {

    plus: function () {

      this.a++

    }

  }

})

vm.plus()

vm.a // 2

watch

  • 类型: { [key: string]: string | Function | Object }
  • 详情:

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.

键是要观察的表达式和值的对象是相应的回调。该值还可以是方法名称的字符串,或包含其他选项的对象。 Vue实例将在实例化时为对象中的每个条目调用$ watch()。

  • 例子:

    • Note that you should not use an arrow function to define a watcher (e.g. searchQuery: newValue => this.updateAutocomplete(newValue)). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.updateAutocomplete will be undefined.
    • 请注意,您不应使用箭头函数来定义观察者(例如,searchQuery:newValue => this.updateAutocomplete(newValue))。原因是箭头函数绑定父上下文,所以这不会是你期望的Vue实例,而this.updateAutocomplete将是未定义的。
    • See also: Instance Methods / Data - vm.$watch
    • Source

var vm = new Vue({

  data: {

    a: 1,

    b: 2,

    c: 3

  },

  watch: {

    a: function (val, oldVal) {

      console.log(\'new: %s, old: %s\', val, oldVal)

    },

    // string method name

    b: \'someMethod\',

    // deep watcher

    c: {

      handler: function (val, oldVal) { /* ... */ },

      deep: true

    }

  }

})

vm.a = 2 // => new: 2, old: 1

 

 

Options / DOM

el

  • 类型: string | HTMLElement
  • 约束: only respected in instance creation via new.只有通过新创建的实例才能得到支持。
  • 详情:

Provide the Vue instance an existing DOM element to mount on. It can be a CSS selector string or an actual HTMLElement.

为Vue实例提供要挂载的现有DOM元素。它可以是CSS选择器字符串或实际的HTMLElement。

After the instance is mounted, the resolved element will be accessible as vm.$el.

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.$el方式访问。

如果在实例化时可以使用此选项,则实例将立即输入编译; 否则,用户将必须显式调用 vm.$mount()来手动启动编译。

The provided element merely serves as a mounting point. Unlike in Vue 1.x, the mounted element will be replaced with Vue-generated DOM in all cases. It is therefore not recommended to mount the root instance to <html> or <body>.

If neither render function nor template option is present, the in-DOM HTML of the mounting DOM element will be extracted as the template. In this case, Runtime + Compiler build of Vue should be used.

所提供的元件仅用作安装点。与Vue 1.x不同,在所有情况下,已安装的元素将被替换为Vue生成的DOM。因此,不建议将根实例挂载到<html>或<body>。

如果没有渲染功能和模板选项都不存在,则将提取装载的DOM元素的DOM内容作为模板。在这种情况下,应该使用Vue的Runtime + Compiler构建。

  • See also:
  • Lifecycle Diagram
  • Runtime + Compiler vs. Runtime-only
  • Source

template

  • 类型: string
  • 详情:

A string template to be used as the markup for the Vue instance. The template will replacethe mounted element. Any existing markup inside the mounted element will be ignored, unless content distribution slots are present in the template.

要用作Vue实例的标记的字符串模板。模板将替换已安装的元件。除非内容分发槽位在模板中,否则安装元素中的任何现有标记都将被忽略。

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 <script type="x-template"> trick to include templates.

如果字符串以#开头,它将被用作querySelector,并使用所选元素的innerHTML作为模板字符串。这允许使用常见的<script type =“x-template”>技巧来包含模板。

From a security perspective, you should only use Vue templates that you can trust. Never use user-generated content as your template.

从安全角度来看,您应该只使用可信任的Vue模板。不要使用用户生成的内容作为模板。

If render function is present in the Vue option, the template will be ignored.

如果Vue选项中存在渲染功能,则模板将被忽略。

  • See also:
  • Lifecycle Diagram
  • Content Distribution with Slots
  • Source

render

  • 类型: (createElement: () => VNode) => VNode
  • 详情:

An alternative to string templates allowing you to leverage the full programmatic power of JavaScript. The render function receives a createElement method as it’s first argument used to create VNodes.

字符串模板的替代方法,可以让您充分利用JavaScript的完整编程能力。 render函数接收createElement方法,因为它是用于创建VNodes的第一个参数。

If the component is a functional component, the render function also receives an extra argument context, which provides access to contextual data since functional components are instance-less.

如果该组件是一个功能组件,则渲染函数还会接收一个额外的参数上下文,该参数上下文提供对上下文数据的访问,因为功能组件是无实例的。

The render function has priority over the render function compiled from template option or in-DOM HTML template of the mounting element which is specified by the el option.

渲染函数优先于从el选项指定的安装元素的template选项或DOM-HTML HTML模板中编译的render函数。

  • See also: Render Functions
  • Source

renderError

New in 2.2.0+

  • 类型: (createElement: () => VNode, error: Error) => VNode
  • 详情:

Only works in development mode.

Provide an alternative render output when the default render function encounters an error. The error will be passed to renderError as the second argument. This is particularly useful when used together with hot-reload.

当默认渲染功能遇到错误时,提供另一种渲染输出。该错误将作为第二个参数传递给renderError。当与热重新加载一起使用时,这是特别有用的。

  • 例子:
  • See also: Render Functions

new Vue({

  render (h) {

    throw new Error(\'oops\')

  },

  renderError (h, err) {

    return h(\'pre\', { style: { color: \'red\' }}, err.stack)

  }

}).$mount(\'#app\')

Options / Lifecycle Hooks

All lifecycle hooks automatically have their this context bound to the instance, so that you can access data, computed properties, and methods. This means you should not use an arrow function to define a lifecycle method (e.g. created: () => this.fetchTodos()). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.fetchTodos will be undefined.

所有生命周期挂钩自动将其上下文绑定到实例,以便您可以访问数据,计算的属性和方法。这意味着您不应该使用箭头函数来定义生命周期方法(例如,创建:()=> this.fetchTodos())。原因是箭头函数绑定父上下文,所以这不会是你期望的Vue实例,而this.fetchTodos将是未定义的。

beforeCreate

  • 类型: Function
  • 详情:

Called synchronously immediately after the instance has been initialized, before data observation and event/watcher setup.

在实例初始化之后,在数据观察和事件/观察器设置之前立即同步调用。

  • See also: Lifecycle Diagram
  • Source

created

  • 类型: Function
  • 详情:

Called synchronously after the instance is created. At this stage, the instance has finished processing the options which means the following have been set up: data observation, computed properties, methods, watch/event callbacks. However, the mounting phase has not been started, and the $el property will not be available yet.

创建实例后同步调用。在这个阶段,实例已经完成处理选项,这意味着已经设置了以下内容:数据观察,计算属性,方法,观察/事件回调。但是,安装阶段尚未启动,并且$ el属性将不可用。

  • See also: Lifecycle Diagram
  • Source

beforeMount

  • 类型: Function
  • 详情:

Called right before the mounting begins: the render function is about to be called for the first time.

在安装开始之前调用:第一次调用render函数。

This hook is not called during server-side rendering.

  • See also: Lifecycle Diagram
  • Source

mounted

  • 类型: Function
  • 详情:

Called after the instance has been mounted, where el is replaced by the newly created vm.$el. If the root instance is mounted to an in-document element, vm.$el will also be in-document when mounted is called.

Note that mounted does not guarantee that all child components have also been mounted. If you want to wait until the entire view has been rendered, you can use vm.$nextTick inside of mounted:

在安装实例之后调用,其中el被新创建的vm。$ el替换。如果将根实例装载到文档元素中,则在挂载被调用时,vm。$ el也将是文档。

请注意,安装不保证所有子组件都已安装。如果你想等到整个视图被渲染,你可以使用vm。$ nextTick里面的:

mounted: function () {

  this.$nextTick(function () {

    // Code that will run only after the

    // entire view has been rendered

  })

}

This hook is not called during server-side rendering.

  • See also: Lifecycle Diagram
  • Source

beforeUpdate

  • 类型: Function
  • 详情:

Called when the data changes, before the virtual DOM is re-rendered and patched.

在数据更改之前调用,在重新渲染和修补虚拟DOM之前。

You can perform further state changes in this hook and they will not trigger additional re-renders.

您可以在此钩子中执行进一步的状态更改,并且不会触发其他重新渲染。

This hook is not called during server-side rendering.

  • See also: Lifecycle Diagram
  • Source

updated

  • 类型: Function
  • 详情:

Called after a data change causes the virtual DOM to be re-rendered and patched.

数据更改后调用导致虚拟DOM被重新渲染和修补。

The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here. However, in most cases you should avoid changing state inside the hook. To react to state changes, it’s usually better to use a computed property or watcher instead.

调用此钩子时,组件的DOM将被更新,因此您可以在此处执行与DOM相关的操作。但是,在大多数情况下,您应该避免在挂钩内更改状态。为了对状态进行更改,通常更好地使用计算属性或观察器。

Note that updated does not guarantee that all child components have also been re-rendered. If you want to wait until the entire view has been re-rendered, you can use vm.$nextTick inside of updated:

请注意,更新不保证所有子组件也被重新呈现。如果你想等到整个视图被重新渲染,你可以使用vm.$nextTick里面的更新:

updated: function () {

  this.$nextTick(function () {

    // Code that will run only after the

    // entire view has been re-rendered

  })

}

This hook is not called during server-side rendering.

  • See also: Lifecycle Diagram
  • Source

activated

  • 类型: Function
  • 详情:

Called when a kept-alive component is activated. 激活保存的组件时调用。

This hook is not called during server-side rendering.

  • See also:
  • Built-in Components - keep-alive
  • Dynamic Components - keep-alive
  • Source

deactivated

  • 类型: Function
  • 详情:

Called when a kept-alive component is deactivated. 当保活组件被停用时调用。

This hook is not called during server-side rendering.

  • See also:
  • Built-in Components - keep-alive
  • Dynamic Components - keep-alive
  • Source

beforeDestroy

  • 类型: Function
  • 详情:

Called right before a Vue instance is destroyed. At this stage the instance is still fully functional.

在Vue实例被销毁之前调用。在这个阶段,这个实例还是完全有效的。

This hook is not called during server-side rendering.

  • See also: Lifecycle Diagram
  • Source

destroyed

  • 类型: Function
  • 详情:

Called after a Vue instance has been destroyed. When this hook is called, all directives of the Vue instance have been unbound, all event listeners have been removed, and all child Vue instances have also been destroyed.

Vue实例被破坏后调用。当调用此钩子时,Vue实例的所有指令都未绑定,所有事件侦听器都已被删除,并且所有子Vue实例也已被销毁。

This hook is not called during server-side rendering.

  • See also: Lifecycle Diagram
  • Source

Options / Assets

directives

  • 类型: Object
  • 详情:

A hash of directives to be made available to the Vue instance.

要向Vue实例提供的指令的散列。

  • See also: Custom Directives
  • Source

filters

  • 类型: Object
  • 详情:

A hash of filters to be made available to the Vue instance.

要向Vue实例提供的过滤器的哈希值。

  • See also: Vue.filter
  • Source

components

  • 类型: Object
  • 详情:

A hash of components to be made available to the Vue instance.

要使Vue实例可用的组件的散列。

  • See also: Components
  • Source

Options / Composition

parent

  • 类型: Vue instance
  • 详情:

Specify the parent instance for the instance to be created. Establishes a parent-child relationship between the two. The parent will be accessible as this.$parent for the child, and the child will be pushed into the parent’s $children array.

Use $parent and $children sparingly - they mostly serve as an escape-hatch. Prefer using props and events for parent-child communication.

指定要创建的实例的父实例。建立两者之间的亲子关系。父母将可以作为该孩子的$ parent来访问,孩子将被推入父项的$ children数组。

省略使用$ parent和$ children - 它们主要用作逃生舱。喜欢使用道具和事件进行亲子沟通。

  • Source

mixins

  • 类型: Array<Object>
  • 详情:

The mixins option accepts an array of mixin objects. These mixin objects can contain instance options like normal instance objects, and they will be merged against the eventual options using the same option merging logic in Vue.extend(). e.g. If your mixin contains a created hook and the component itself also has one, both functions will be called.

mixins选项接受一组mixin对象。这些mixin对象可以包含像常规实例对象的实例选项,并且它们将使用Vue.extend()中相同的选项合并逻辑与最终选项进行合并。例如如果你的mixin包含一个创建的钩子,而组件本身也有一个,这两个函数都将被调用。

Mixin hooks are called in the order they are provided, and called before the component’s own hooks.

Mixin钩子按照它们提供的顺序调用,并在组件自己的钩子之前调用。

  • 例子:
  • See also: Mixins
  • Source

var mixin = {

  created: function () { console.log(1) }

}

var vm = new Vue({

  created: function () { console.log(2) },

  mixins: [mixin]

})

// => 1

// => 2

extends

  • 类型: Object | Function
  • 详情:

Allows declaratively extending another component (could be either a plain options object or a constructor) without having to use Vue.extend. This is primarily intended to make it easier to extend between single file components.

This is similar to mixins, the difference being that the component’s own options takes higher priority than the source component being extended.

允许声明性地扩展另一个组件(可以是一个简单的选项对象或构造函数),而不必使用Vue.extend。这主要是为了使在单个文件组件之间更容易扩展。

这与mixins类似,区别在于组件自身的选项比要扩展的源组件具有更高的优先级。

  • 例子:
  • Source

var CompA = { ... }

// extend CompA without having to call `Vue.extend` on either

var CompB = {

  extends: CompA,

  ...

}

provide / inject

New in 2.2.0+

  • 类型:
  • provide: Object | () => Object
  • inject: Array<string> | { [key: string]: string | Symbol }
  • 详情:

provide and inject are primarily provided for advanced plugin / component library use cases. It is NOT recommended to use them in generic application code.

提供和注入主要用于高级插件/组件库用例。不建议在通用应用程序代码中使用它们。

This pair of options are used together to allow an ancestor component to serve as a dependency injector for its all descendants, regardless of how deep the component hierarchy is, as long as they are in the same parent chain. If you are familiar with React, this is very similar to React’s context feature.

这对选项一起用于允许祖先组件充当其所有后代的依赖注入器,而不管组件层次结构如何深入,只要它们在同一个父链中即可。如果您熟悉React,这与React的上下文功能非常相似。

The provide option should be an object or a function that returns an object. This object contains the properties that are available for injection into its descendants.

提供选项应该是返回对象的对象或函数。此对象包含可用于注入其后代的属性。You can use ES2015 Symbols as keys in this object, but only in environments that natively support Symbol and Reflect.ownKeys.

您可以在此对象中使用ES2015符号作为键,但仅在本机支持Symbol和Reflect.ownKeys的环境中使用。

 

The inject options should be either an Array of strings or an object where the keys stand for the local binding name, and the value being the key (string or Symbol) to search for in available injections.

注入选项应该是一个字符串数组或一个对象,其中键代表本地绑定名称,该值是在可用注入中搜索的键(字符串或符号)。

 

Note: the provide and inject bindings are NOT reactive. This is intentional. However, if you pass down an observed object, properties on that object do remain reactive.

注意:提供和注入绑定没有反应。这是有意的。但是,如果您传递观察对象,则该对象上的属性将保持响应。

  • 例子:
  • With ES2015 Symbols, function provide and object inject:
  • The next 2 examples work with Vue 2.2.1+. Below that version, injected values were resolved after the props and the data initialization.

    • 接下来的2个例子使用Vue 2.2.1+。在该版本之下,注入的值在道具和数据初始化后被解析。
    • Using an injected value as the default for a prop:

      • 使用注入值作为道具的默认值:
      • Using an injected value as data entry:

var Provider = {

  provide: {

    foo: \'bar\'

  },

  // ...

}

var Child = {

  inject: [\'foo\'],

  created () {

    console.log(this.foo) // => "bar"

  }

  // ...

}

const s = Symbol()

const Provider = {

  provide () {

    return {

      [s]: \'foo\'

    }

  }

}

const Child = {

  inject: { s },

  // ...

}

const Child = {

  inject: [\'foo\'],

  props: {

    bar: {

      default () {

        return this.foo

      }

    }

  }

}

const Child = {

  inject: [\'foo\'],

  data () {

    return {

      bar: this.foo

    }

  }

}

Options / Misc

name

  • 类型: string
  • 约束: only respected when used as a component option.

    • 仅当作为组件选项使用时才被尊重。
    • 详情:

Allow the component to recursively invoke itself in its template. Note that when a component is registered globally with Vue.component(), the global ID is automatically set as its name.

允许组件在其模板中递归调用自身。请注意,当组件使用Vue.component()全局注册时,全局ID将自动设置为其名称。

 

Another benefit of specifying a name option is debugging. Named components result in more helpful warning messages. Also, when inspecting an app in the vue-devtools, unnamed components will show up as <AnonymousComponent>, which isn’t very informative. By providing the name option, you will get a much more informative component tree.

指定名称选项的另一个好处是调试。命名组件导致更有用的警告消息。此外,当检查vue-devtools中的应用程序时,未命名的组件将显示为<AnonymousComponent>,这不是很丰富。通过提供名称选项,您将获得更多信息的组件树。

  • Source

delimiters

  • 类型: Array<string>
  • 默认值: ["{{", "}}"]
  • 约束: This option is only available in the full build, with in-browser compilation.

    • 此选项仅在完整版本中可用,并具有浏览器内编译
    • 详情:

Change the plain text interpolation delimiters.

更改纯文本插值分隔符。

  • 例子:
  • Source

new Vue({

  delimiters: [\'${\', \'}\']

})

// Delimiters changed to ES6 template string style

functional

  • 类型: boolean
  • 详情:

Causes a component to be stateless (no data) and instanceless (no this context). They are only a render function that returns virtual nodes making them much cheaper to render.

使组件成为无状态(无数据)和无实例(无此上下文)。它们只是一个渲染函数,返回虚拟节点,使其渲染成本更低。

  • See also: Functional Components
  • Source

model

New in 2.2.0

  • 类型: { prop?: string, event?: string }
  • 详情:

Allows a custom component to customize the prop and event used when it’s used with v-model. By default, v-model on a component uses value as the prop and input as the event, but some input types such as checkboxes and radio buttons may want to use the value prop for a different purpose. Using the model option can avoid the conflict in such cases.

允许自定义组件定制与v-model一起使用的支架和事件。默认情况下,组件上的v-model使用值作为参数,并将其作为事件输入,但是某些输入类型(如复选框和单选按钮)可能需要使用值为不同的目的。使用模型选项可以避免这种情况下的冲突。

  • 例子:
  • The above will be equivalent to:

Vue.component(\'my-checkbox\', {

  model: {

    prop: \'checked\',

    event: \'change\'

  },

  props: {

    // this allows using the `value` prop for a different purpose

    value: String,

    // use `checked` as the prop which take the place of `value`

    checked: {

      type: Number,

      default: 0

    }

  },

  // ...

})

<my-checkbox v-model="foo" value="some value"></my-checkbox>

<my-checkbox

  :checked="foo"

  @change="val => { foo = val }"

  value="some value">

</my-checkbox>

inheritAttrs

New in 2.4.0+

  • 类型: boolean
  • 默认值: true
  • 详情:

By default, parent scope attribute bindings that are not recognized as props will “fallthrough” and be applied to the root element of the child component as normal HTML attributes. When authoring a component that wraps a target element or another component, this may not always be the desired behavior. By setting inheritAttrs to false, this default behavior can be disabled. The attributes are available via the $attrsinstance property (also new in 2.4) and can be explicitly bound to a non-root element using v-bind.

Note: this option does not affect class and style bindings.

默认情况下,未被识别为道具的父范围属性绑定将“通过”并作为普通HTML属性应用于子组件的根元素。当创建包装目标元素或其他组件的组件时,这可能并不总是所需的行为。通过将inheritAttrs设置为false,可以禁用此默认行为。这些属性可以通过$ attrsinstance属性(在2.4中也是新的)可用,并且可以使用v-bind显式绑定到非根元素。

注意:此选项不影响类和样式绑定。

comments

New in 2.4.0+

  • 类型: boolean
  • 默认值: false
  • 约束: This option is only available in the full build, with in-browser compilation.

    • 此选项仅在完整版本中可用,并具有浏览器内编译
    • 详情:

When set to true, will preserve and render HTML comments found in templates. The default behavior is discarding them.

设置为true时,将保留并呈现在模板中发现的HTML注释。默认行为是丢弃它们。

Instance Properties

vm.$data

  • 类型: Object
  • 详情:

The data object that the Vue instance is observing. The Vue instance proxies access to the properties on its data object.

Vue实例正在观察的数据对象。 Vue实例代理访问其数据对象上的属性。

  • See also: Options / Data - data
  • Source

vm.$props

New in 2.2.0+

  • 类型: Object
  • 详情:

An object representing the current props a component has received. The Vue instance proxies access to the properties on its props object.

表示组件所接收的当前道具的对象。 Vue实例代理访问其道具对象上的属性。

vm.$el

  • 类型: HTMLElement
  • Read only
  • 详情:

The root DOM element that the Vue instance is managing.

Vue实例正在管理的根DOM元素。

  • Source

vm.$options

  • 类型: Object
  • Read only
  • 详情:

The instantiation options used for the current Vue instance. This is useful when you want to include custom properties in the options:

用于当前Vue实例的实例化选项。当您希望在选项中包含自定义属性时,这很有用:

new Vue({

  customOption: \'foo\',

  created: function () {

    console.log(this.$options.customOption) // => \'foo\'

  }

})

  • Source

vm.$parent

  • 类型: Vue instance
  • Read only
  • 详情:

The parent instance, if the current instance has one.

父实例,如果当前实例有一个。

  • Source

vm.$root

  • 类型: Vue instance
  • Read only
  • 详情:

The root Vue instance of the current component tree. If the current instance has no parents this value will be itself.

当前组件树的根Vue实例。如果当前实例没有父级,则此值将自身。

  • Source

vm.$children

  • 类型: Array<Vue instance>
  • Read only
  • 详情:

The direct child components of the current instance. Note there’s no order guarantee for$children, and it is not reactive. If you find yourself trying to use $children for data binding, consider using an Array and v-for to generate child components, and use the Array as the source of truth.

当前实例的直接子组件。注意,$ children没有订单保证,它不是被动的。如果您发现自己尝试使用$ children进行数据绑定,请考虑使用Array和v-for生成子组件,并使用Array作为真值的来源。

  • Source

vm.$slots

  • 类型: { [name: string]: ?Array<VNode> }
  • Read only
  • 详情:

Used to programmatically access content distributed by slots. Each named slot has its own corresponding property (e.g. the contents of slot="foo" will be found at vm.$slots.foo). The default property contains any nodes not included in a named slot.

用于以编程方式访问由插槽分发的内容。每个命名的插槽都有自己的对应属性(例如,slot =“foo”的内容将在vm。$ slots.foo中找到)。默认属性包含未包含在命名槽中的任何节点。

Accessing vm.$slots is most useful when writing a component with a render function.

使用渲染功能编写组件时,访问vm。$插槽最为有用。

  • 例子:
  • See also:
  • <slot> Component
  • Content Distribution with Slots
  • Render Functions - Slots
  • Source

<blog-post>

  <h1 slot="header">

    About Me

  </h1>

  <p>Here\'s some page content, which will be included in vm.$slots.default, because it\'s not inside a named slot.</p>

  <p slot="footer">

    Copyright 2016 Evan You

  </p>

  <p>If I have some content down here, it will also be included in vm.$slots.default.</p>.

</blog-post>

Vue.component(\'blog-post\', {

  render: function (createElement) {

    var header = this.$slots.header

    var body   = this.$slots.default

    var footer = this.$slots.footer

    return createElement(\'div\', [

      createElement(\'header\', header),

      createElement(\'main\', body),

      createElement(\'footer\', footer)

    ])

  }

})

vm.$scopedSlots

New in 2.1.0+

  • 类型: { [name: string]: props => VNode | Array<VNode> }
  • Read only
  • 详情:

Used to programmatically access scoped slots. For each slot, including the default one, the object contains a corresponding function that returns VNodes.

用于以编程方式访问作用域。对于每个插槽,包括默认的插槽,该对象包含一个返回VNodes的相应函数。

 

Accessing vm.$scopedSlots is most useful when writing a component with a render function.

使用渲染功能编写组件时,访问vm.$scopedSlots最为有用。

  • See also:
  • <slot> Component
  • Scoped Slots
  • Render Functions - Slots

vm.$refs

  • 类型: Object
  • Read only
  • 详情:

An object that holds child components that have ref registered.

保存已注册的子组件的对象。

  • See also:
  • Child Component Refs
  • Special Attributes - ref
  • Source

vm.$isServer

  • 类型: boolean
  • Read only
  • 详情:

Whether the current Vue instance is running on the server.

当前的Vue实例是否在服务器上运行。

  • See also: Server-Side Rendering
  • Source

vm.$attrs

  • 类型: { [key: string]: string }
  • Read only
  • 详情:

Contains parent-scope attribute bindings (except for class and style) that are not recognized (and extracted) as props. When a component doesn’t have any declared props, this essentially contains all parent-scope bindings (except for class and style), and can be passed down to an inner component via v-bind="$attrs" - useful when creating higher-order components.

包含无法识别(并提取)作为道具的父范围属性绑定(类和样式除外)。当组件没有任何声明的道具时,它基本上包含所有父级范围绑定(除了类和样式),并且可以通过v-bind =“$ attrs”传递到内部组件 - 在创建更高版本时很有用顺序组件。

  • Source

vm.$listeners

  • 类型: { [key: string]: Function | Array<Function> }
  • Read only
  • 详情:

Contains parent-scope v-on event listeners (without .native modifiers). This can be passed down to an inner component via v-on="$listeners" - useful when creating higher-order components.

包含父范围v-on事件侦听器(没有.native修饰符)。这可以通过v-on =“$ listeners”传递给内部组件 - 在创建高阶组件时很有用。

  • Source

Instance Methods / Data

vm.$watch( expOrFn, callback, [options] )

  • Arguments:
  • {string | Function} expOrFn
  • {Function | Object} callback
  • {Object} [options]
  • {boolean} deep
  • {boolean} immediate
  • Returns: {Function} unwatch
  • 用法:

Watch an expression or a computed function on the Vue instance for changes. The callback gets called with the new value and the old value. The expression only accepts dot-delimited paths. For more complex expressions, use a function instead.

在Vue实例上观察表达式或计算函数以进行更改。使用新值和旧值调用回调。该表达式仅接受点分隔的路径。对于更复杂的表达式,请改用函数。

  • Source

Note: when mutating (rather than replacing) an Object or an Array, the old value will be the same as new value because they reference the same Object/Array. Vue doesn’t keep a copy of the pre-mutate value.

注意:当突变(而不是替换)对象或数组时,旧值将与新值相同,因为它们引用了相同的对象/数组。 Vue不保留突变前值的副本。

  • 例子:
  • vm.$watch returns an unwatch function that stops firing the callback:
  • Option: deep

// keypath

vm.$watch(\'a.b.c\', function (newVal, oldVal) {

  // do something

})

// function

vm.$watch(

  function () {

    return this.a + this.b

  },

  function (newVal, oldVal) {

    // do something

  }

)

var unwatch = vm.$watch(\'a\', cb)

// later, teardown the watcher

unwatch()

To also detect nested value changes inside Objects, you need to pass in deep: true in the options argument. Note that you don’t need to do so to listen for Array mutations.

要检测对象内的嵌套值更改,您需要在options参数中传入deep:true。请注意,您不需要这样做来侦听Array突变。

vm.$watch(\'someObject\', callback, {

  deep: true

})

vm.someObject.nestedValue = 123

// callback is fired

  • Option: immediate

Passing in immediate: true in the option will trigger the callback immediately with the current value of the expression:

传递立即数:在选项中的true将立即触发回调与表达式的当前值:

vm.$watch(\'a\', callback, {

  immediate: true

})

// `callback` is fired immediately with current value of `a`

vm.$set( target, key, value )

  • Arguments:
  • {Object | Array} target
  • {string | number} key
  • {any} value
  • Returns: the set value.
  • 用法:

This is the alias of the global Vue.set.

  • See also: Vue.set
  • Source

vm.$delete( target, key )

  • Arguments:
  • {Object | Array} target
  • {string | number} key
  • 用法:

This is the alias of the global Vue.delete.

  • See also: Vue.delete
  • Source

Instance Methods / Events

vm.$on( event, callback )

  • Arguments:
  • {string | Array<string>} event (array only supported in 2.2.0+)
  • {Function} callback
  • 用法:

Listen for a custom event on the current vm. Events can be triggered by vm.$emit. The callback will receive all the additional arguments passed into these event-triggering methods.

在当前vm上收听自定义事件。事件可以由vm。$ emit触发。回调将接收传递到这些事件触发方法的所有其他参数。

  • 例子:
  • Source

vm.$on(\'test\', function (msg) {

  console.log(msg)

})

vm.$emit(\'test\', \'hi\')

// => "hi"

vm.$once( event, callback )

  • Arguments:
  • {string} event
  • {Function} callback
  • 用法:

Listen for a custom event, but only once. The listener will be removed once it triggers for the first time.

听一个自定义的事件,但只有一次。一旦它首次触发,侦听器将被删除。

  • Source

vm.$off( [event, callback] )

  • Arguments:
  • {string | Array<string>} event (array only supported in 2.2.2+)
  • {Function} [callback]
  • 用法:

Remove custom event listener(s).

  • If no arguments are provided, remove all event listeners;

    • 如果没有提供参数,请删除所有事件侦听器;
    • If only the event is provided, remove all listeners for that event;

      • 如果仅提供事件,请删除该事件的所有侦听器;
      • If both event and callback are given, remove the listener for that specific callback only.

        • 如果同时提供事件和回调函数,则仅删除该特定回调函数的侦听器。
        • Source

vm.$emit( event, […args] )

  • Arguments:
  • {string} event
  • [...args]

Trigger an event on the current instance. Any additional arguments will be passed into the listener’s callback function.

触发当前实例上的事件。任何其他参数将被传递到监听器的回调函数中。

  • Source

Instance Methods / Lifecycle

vm.$mount( [elementOrSelector] )

  • Arguments:
  • {Element | string} [elementOrSelector]
  • {boolean} [hydrating]
  • Returns: vm - the instance itself
  • 用法:

If a Vue instance didn’t receive the el option at instantiation, it will be in “unmounted” state, without an associated DOM element. vm.$mount() can be used to manually start the mounting of an unmounted Vue instance.

If elementOrSelector argument is not provided, the template will be rendered as an off-document element, and you will have to use native DOM API to insert it into the document yourself.

如果Vue实例在实例化时没有收到el选项,则它将处于“未安装”状态,而不包含关联的DOM元素。 vm。$ mount()可用于手动启动未安装的Vue实例的安装。

如果未提供elementOrSelector参数,则该模板将作为非文档元素呈现,您将不得不使用本机DOM API将其自动插入到文档中。

The method returns the instance itself so you can chain other instance methods after it.

  • 例子:
  • See also:
  • Lifecycle Diagram
  • Server-Side Rendering
  • Source

var MyComponent = Vue.extend({

  template: \'<div>Hello!</div>\'

})

// create and mount to #app (will replace #app)

new MyComponent().$mount(\'#app\')

// the above is the same as:

new MyComponent({ el: \'#app\' })

// or, render off-document and append afterwards:

var component = new MyComponent().$mount()

document.getElementById(\'app\').appendChild(component.$el)

vm.$forceUpdate()

  • 用法:

Force the Vue instance to re-render. Note it does not affect all child components, only the instance itself and child components with inserted slot content.

  • Source

vm.$nextTick( [callback] )

  • Arguments:
  • {Function} [callback]
  • 用法:

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. This is the same as the global Vue.nextTick, except that the callback’s this context is automatically bound to the instance calling this method.

延迟在下一个DOM更新周期后执行的回调。在更改一些数据以等待DOM更新后立即使用它。这与全局Vue.nextTick相同,只是回调的上下文自动绑定到调用此方法的实例。

New in 2.1.0+: returns a Promise if no callback is provided and Promise is supported in the execution environment. Please note that Vue does not come with a Promise polyfill, so if you target browsers that don’t support Promises natively (looking at you, IE), you will have to provide a polyfill yourself.

  • 例子:
  • See also:
  • Vue.nextTick
  • Async Update Queue
  • Source

new Vue({

  // ...

  methods: {

    // ...

    example: function () {

      // modify data

      this.message = \'changed\'

      // DOM is not updated yet

      this.$nextTick(function () {

        // DOM is now updated

        // `this` is bound to the current instance

        this.doSomethingElse()

      })

    }

  }

})

vm.$destroy()

  • 用法:

Completely destroy a vm. Clean up its connections with other existing vms, unbind all its directives, turn off all event listeners.

完全毁灭一个vm 清理与其他现有vms的连接,取消绑定其所有指令,关闭所有事件侦听器。

Triggers the beforeDestroy and destroyed hooks.

In normal use cases you shouldn’t have to call this method yourself. Prefer controlling the lifecycle of child components in a data-driven fashion using v-ifand v-for.

  • See also: Lifecycle Diagram
  • Source

Directives

v-text

  • Expects: string
  • 详情:

Updates the element’s textContent. If you need to update the part of textContent, you should use {{ Mustache }} interpolations.

更新元素的textContent。如果您需要更新textContent的部分,您应该使用{{Mustache}}插值。

  • 例子:
  • See also: Data Binding Syntax - Interpolations
  • Source

<span v-text="msg"></span>

<!-- same as -->

<span>{{msg}}</span>

v-html

  • Expects: string
  • 详情:

Updates the element’s innerHTML. Note that the contents are inserted as plain HTML - they will not be compiled as Vue templates. If you find yourself trying to compose templates using v-html, try to rethink the solution by using components instead.

更新元素的innerHTML。请注意,内容是以纯HTML插入的 - 它们不会被编译为Vue模板。如果您发现自己正在使用v-html编写模板,请尝试使用组件来重新思考解决方案。

Dynamically rendering arbitrary HTML on your website can be very dangerous because it can easily lead to XSS attacks. Only use v-html on trusted content and never on user-provided content.

在您的网站上动态渲染任意HTML可能非常危险,因为它很容易导致XSS攻击。只能在受信任的内容上使用v-html,从不使用用户提供的内容。

  • 例子:
  • See also: Data Binding Syntax - Interpolations
  • Source

<div v-html="html"></div>

v-show

  • Expects: any
  • 用法:

Toggle’s the element’s display CSS property based on the truthy-ness of the expression value.

根据表达式值的真实性,切换元素的display CSS属性。

This directive triggers transitions when its condition changes.

该指令在条件变化时触发转换。

  • See also: Conditional Rendering - v-show
  • Source

v-if

  • Expects: any
  • 用法:

Conditionally render the element based on the truthy-ness of the expression value. The element and its contained directives / components are destroyed and re-constructed during toggles. If the element is a <template> element, its content will be extracted as the conditional block.

有条件地根据表达式值的真实性来渲染元素。元素及其包含的指令/组件在切换期间被销毁和重新构建。如果元素是<template>元素,则其内容将被提取为条件块。

This directive triggers transitions when its condition changes.

该指令在条件变化时触发转换。

When used together with v-if, v-for has a higher priority than v-if. See the list rendering guide for detail.

当与v-if一起使用时,v-for优先级高于v-if。有关详细信息,请参阅列表渲染指南

  • See also: Conditional Rendering - v-if
  • Source

v-else

  • Does not expect expression
  • 约束: previous sibling element must have v-if or v-else-if.

    • 前一个兄弟元素必须有V-如果或V-ELSE-IF。
    • 用法:

Denote the “else block” for v-if or a v-if/v-else-if chain.

<div v-if="Math.random() > 0.5">

  Now you see me

</div>

<div v-else>

  Now you don\'t

</div>

  • See also: Conditional Rendering - v-else
  • Source

v-else-if

New in 2.1.0+

  • Expects: any

    • 约束: previous sibling element must have v-if or v-else-if.以前的兄弟元素必须有v-if或者v-else-if。
    • 用法:

Denote the “else if block” for v-if. Can be chained.

<div v-if="type === \'A\'">

  A

</div>

<div v-else-if="type === \'B\'">

  B

</div>

<div v-else-if="type === \'C\'">

  C

</div>

<div v-else>

  Not A/B/C

</div>

  • See also: Conditional Rendering - v-else-if

v-for

  • Expects: Array | Object | number | string
  • 用法:

Render the element or template block multiple times based on the source data. The directive’s value must use the special syntax alias in expression to provide an alias for the current element being iterated on:

基于源数据多次渲染元素或模板块。指令的值必须使用表达式中的特殊语法别名为当前迭代的元素提供一个别名:

<div v-for="item in items">

  {{ item.text }}

</div>

Alternatively, you can also specify an alias for the index (or the key if used on an Object):

或者,您还可以为索引指定别名(或在对象上使用的键):

<div v-for="(item, index) in items"></div>

<div v-for="(val, key) in object"></div>

<div v-for="(val, key, index) in object"></div>

The default behavior of v-for will try to patch the elements in-place without moving them. To force it to reorder elements, you need to provide an ordering hint with the keyspecial attribute:

v-for的默认行为将尝试在不移动它们的地方修补元素。要强制它重新排序元素,您需要提供一个带有keyspecial属性的排序提示:

<div v-for="item in items" :key="item.id">

  {{ item.text }}

</div>

When used together with v-if, v-for has a higher priority than v-if. See the list rendering guide for details.

当与v-if一起使用时,v-for优先级高于v-if。有关详细信息,请参阅列表渲染指南

The detailed usage for v-for is explained in the guide section linked below.

详细用法见下面的链接

  • See also:
  • List Rendering
  • key
  • Source

v-on

  • Shorthand: @
  • Expects: Function | Inline Statement | Object
  • Argument: event
  • Modifiers:
  • .stop - call event.stopPropagation().
  • .prevent - call event.preventDefault().
  • .capture - add event listener in capture mode.
  • .self - only trigger handler if event was dispatched from this element.
  • .{keyCode | keyAlias} - only trigger handler on certain keys.
  • .native - listen for a native event on the root element of component.
  • .once - trigger handler at most once.
  • .left - (2.2.0+) only trigger handler for left button mouse events.
  • .right - (2.2.0+) only trigger handler for right button mouse events.
  • .middle - (2.2.0+) only trigger handler for middle button mouse events.
  • .passive - (2.3.0+) attaches a DOM event with { passive: true }.
  • 用法:

Attaches an event listener to the element. The event type is denoted by the argument. The expression can be a method name, an inline statement, or omitted if there are modifiers present.

Starting in 2.4.0+, v-on also supports binding to an object of event/listener pairs without an argument. Note when using the object syntax, it does not support any modifiers.

When used on a normal element, it listens to native DOM events only. When used on a custom element component, it also listens to custom events emitted on that child component.

When listening to native DOM events, the method receives the native event as the only argument. If using inline statement, the statement has access to the special $eventproperty: v-on:click="handle(\'ok\', $event)".

 

将事件侦听器附加到元素。事件类型由参数表示。表达式可以是方法名称,内联语句,如果存在修饰符,则可以省略。

从2.4.0+开始,v-on还支持绑定到没有参数的事件/监听器对的对象。注意当使用对象语法时,它不支持任何修饰符。

当在普通元素上使用时,它只侦听本机DOM事件。当在自定义元素组件上使用时,它还会监听在该子组件上发布的自定义事件。

当侦听本机DOM事件时,该方法将接收本机事件作为唯一的参数。如果使用内联语句,该语句可以访问特殊的$ eventproperty:v-on:click =“handle(\'ok\',$ event)”。

  • 例子:
  • Listening to custom events on a child component (the handler is called when “my-event” is emitted on the child):

    • 聆听子组件上的自定义事件(当孩子发出“my-event”时调用该处理程序)):
    • See also:
    • Event Handling
    • Components - Custom Events
    • Source

<!-- method handler -->

<button v-on:click="doThis"></button>

<!-- object syntax (2.4.0+) -->

<button v-on="{ mousedown: doThis, mouseup: doThat }"></button>

<!-- inline statement -->

<button v-on:click="doThat(\'hello\', $event)"></button>

<!-- shorthand -->

<button @click="doThis"></button>

<!-- stop propagation -->

<button @click.stop="doThis"></button>

<!-- prevent default -->

<button @click.prevent="doThis"></button>

<!-- prevent default without expression -->

<form @submit.prevent></form>

<!-- chain modifiers -->

<button @click.stop.prevent="doThis"></button>

<!-- key modifier using keyAlias -->

<input @keyup.enter="onEnter">

<!-- key modifier using keyCode -->

<input @keyup.13="onEnter">

<!-- the click event will be triggered at most once -->

<button v-on:click.once="doThis"></button>

<my-component @my-event="handleThis"></my-component>

<!-- inline statement -->

<my-component @my-event="handleThis(123, $event)"></my-component>

<!-- native event on component -->

<my-component @click.native="onClick"></my-component>

 

v-bind

  • 速记: :
  • 预期: any (with argument) | Object (without argument)
  • 参数: attrOrProp (optional)
  • 编辑器:
  • .prop - Bind as a DOM property instead of an attribute (what’s the difference?). If the tag is a component then .prop will set the property on the component’s $el.
  • .camel - (2.1.0+) transform the kebab-case attribute name into camelCase.
  • .sync - (2.3.0+) a syntax sugar that expands into a v-on handler for updating the bound value.
  • 用法:

    • 绑定为DOM属性而不是属性(有什么区别?)。如果标签是组件,那么.prop将在组件的$ el上设置属性。

    • (2.1.0+)将kebab-case属性名称转换为camelCase。

    • (2.3.0+)扩展为v-on处理程序以更新绑定值的语法糖。

Dynamically bind one or more attributes, or a component prop to an expression.

动态地将一个或多个属性或组件支持绑定到表达式。

When used to bind the class or style attribute, it supports additional value types such as Array or Objects. See linked guide section below for more details.

When used for prop binding, the prop must be properly declared in the child component.

When used without an argument, can be used to bind an object containing attribute name-value pairs. Note in this mode class and style does not support Array or Objects.

当用于绑定类或样式属性时,它支持其他值类型,例如Array或Objects。有关详细信息,请参阅以下链接指南部分当用于支撑装订时,支柱必须在子组件中正确声明。当没有参数使用时,可以用于绑定包含属性名称 - 值对的对象。注意在这种模式下,类和样式不支持Array或Objects。

  • 例子:
  • The .camel modifier allows camelizing a v-bind attribute name when using in-DOM templates, e.g. the SVG viewBox attribute:

    • .camel修饰符允许在使用DOM模板时使用v-bind属性名称。 SVG viewBox属性:
    • .camel is not needed if you are using string templates, or compiling with vue-loader/vueify.
    • 如果您使用字符串模板,或使用vue-loader / vueify进行编译,则不需要.camel。
    • See also:
    • Class and Style Bindings
    • Components - Props
    • Components - .sync Modifier
    • Source

<!-- bind an attribute -->

<img v-bind:src="imageSrc">

<!-- shorthand -->

<img :src="imageSrc">

<!-- with inline string concatenation -->

<img :src="\'/path/to/images/\' + fileName">

<!-- class binding -->

<div :class="{ red: isRed }"></div>

<div :class="[classA, classB]"></div>

<div :class="[classA, { classB: isB, classC: isC }]">

<!-- style binding -->

<div :style="{ fontSize: size + \'px\' }"></div>

<div :style="[styleObjectA, styleObjectB]"></div>

<!-- binding an object of attributes -->

<div v-bind="{ id: someProp, \'other-attr\': otherProp }"></div>

<!-- DOM attribute binding with prop modifier -->

<div v-bind:text-content.prop="text"></div>

<!-- prop binding. "prop" must be declared in my-component. -->

<my-component :prop="someThing"></my-component>

<!-- pass down parent props in common with a child component -->

<child-component v-bind="$props"></child-component>

<!-- XLink -->

<svg><a :xlink:special="foo"></a></svg>

<svg :view-box.camel="viewBox"></svg>

v-model

  • Expects: varies based on value of form inputs element or output of components 根据表单输入元素的值或组件的输出而变化
  • Limited to:
  • <input>
  • <select>
  • <textarea>
  • components
  • Modifiers:
  • .lazy - listen to change events instead of input
  • .number - cast input string to numbers
  • .trim - trim input
  • 用法:

Create a two-way binding on a form input element or a component. For detailed usage and other notes, see the Guide section linked below.

在表单输入元素或组件上创建双向绑定。有关详细的用法和其他注意事项,请参阅下面的指导部分。

  • See also:
  • Form Input Bindings
  • Components - Form Input Components using Custom Events
  • Source

v-pre

  • Does not expect expression
  • 用法:

Skip compilation for this element and all its children. You can use this for displaying raw mustache tags. Skipping large numbers of nodes with no directives on them can also speed up compilation.

跳过此元素及其所有子项的编译。您可以使用它来显示原始的胡须标签。跳过大量没有指令的节点也可以加快编译速度。

  • 例子:
  • Source

<span v-pre>{{ this will not be compiled }}</span>

v-cloak

  • Does not expect expression
  • 用法:

This directive will remain on the element until the associated Vue instance finishes compilation. Combined with CSS rules such as [v-cloak] { display: none }, this directive can be used to hide un-compiled mustache bindings until the Vue instance is ready.

该指令将保留在元素上,直到关联的Vue实例完成编译。结合CSS规则,如[v-cloak] {display:none},该指令可用于隐藏未编译的胡须绑定,直到Vue实例准备就绪。

  • 例子:
  • The <div> will not be visible until the compilation is done.
  • Source

[v-cloak] {

  display: none;

}

<div v-cloak>

  {{ message }}

</div>

v-once

  • Does not expect expression
  • 详情:

Render the element and component once only. On subsequent re-renders, the element/component and all its children will be treated as static content and skipped. This can be used to optimize update performance.

仅渲染元素和组件。在后续重新渲染中,元素/组件及其所有子项将被视为静态内容并被跳过。这可以用于优化更新性能。

<!-- single element -->

<span v-once>This will never change: {{msg}}</span>

<!-- the element have children -->

<div v-once>

  <h1>comment</h1>

  <p>{{msg}}</p>

</div>

<!-- component -->

<my-component v-once :comment="msg"></my-component>

<!-- `v-for` directive -->

<ul>

  <li v-for="i in list" v-once>{{i}}</li>

</ul>

  • See also:
  • Data Binding Syntax - interpolations
  • Components - Cheap Static Components with v-once
  • Source

Special Attributes

key

  • Expects: number | string

The key special attribute is primarily used as a hint for Vue’s virtual DOM algorithm to identify VNodes when diffing the new list of nodes against the old list. Without keys, Vue uses an algorithm that minimizes element movement and tries to patch/reuse elements of the same type in-place as much as possible. With keys, it will reorder elements based on the order change of keys, and elements with keys that are no longer present will always be removed/destroyed.

Children of the same common parent must have unique keys. Duplicate keys will cause render errors.

关键的特殊属性主要用作Vue的虚拟DOM算法的提示,以便在将新的节点列表与旧列表分开时识别VNodes。没有键,Vue使用最小化元素移动的算法,并尝试尽可能多地对同一类型的元素进行修补/重用。使用键,它将根据键的顺序改变对元素重新排序,并且具有不再存在的键的元素将始终被删除/销毁。同一父母的子女必须具有唯一的密钥。重复的键将导致渲染错误。

The most common use case is combined with v-for:

最常见的用例与v-for结合使用:

<ul>

  <li v-for="item in items" :key="item.id">...</li>

</ul>

It can also be used to force replacement of an element/component instead of reusing it. This can be useful when you want to:

它也可用于强制更换元素/组件,而不是重用它。当您想要:

  • Properly trigger lifecycle hooks of a component
  • Trigger transitions

For example:

<transition>

  <span :key="text">{{ text }}</span>

</transition>

When text changes, the <span> will always be replaced instead of patched, so a transition will be triggered.

当文本更改时,将始终替换<span>而不是修补,因此将触发转换。

  • Source

ref

  • Expects: string

ref is used to register a reference to an element or a child component. The reference will be registered under the parent component’s $refs object. If used on a plain DOM element, the reference will be that element; if used on a child component, the reference will be component instance:

ref用于注册对元素或子组件的引用。引用将在父组件的$ refs对象下注册。如果在普通的DOM元素上使用,引用将是该元素; 如果在子组件上使用,则引用将是组件实例:

<!-- vm.$refs.p will be the DOM node -->

<p ref="p">hello</p>

<!-- vm.$refs.child will be the child comp instance -->

<child-comp ref="child"></child-comp>

When used on elements/components with v-for, the registered reference will be an Array containing DOM nodes or component instances.

An important note about the ref registration timing: because the refs themselves are created as a result of the render function, you cannot access them on the initial render - they don’t exist yet! $refs is also non-reactive, therefore you should not attempt to use it in templates for data-binding.

当用于具有v-for的元素/组件时,注册的引用将是包含DOM节点或组件实例的数组。关于引用注册时间的一个重要注意事项:由于参考自身是由于渲染功能而创建的,因此您无法在初始渲染上访问它们 - 它们不存在! $ ref也是非反应的,因此您不应该尝试在模板中使用它进行数据绑定。

  • See also: Child Component Refs
  • Source

slot

  • Expects: string

Used on content inserted into child components to indicate which named slot the content belongs to.

用于插入到子组件中的内容,以指示内容属于哪个指定的槽。

For detailed usage, see the guide section linked below.

  • See also: Named Slots
  • Source

is

  • Expects: string

Used for dynamic components and to work around limitations of in-DOM templates.

For example:

<!-- component changes when currentView changes -->

<component v-bind:is="currentView"></component>

<!-- necessary because `<my-row>` would be invalid inside -->

<!-- a `<table>` element and so would be hoisted out      -->

<table>

  <tr is="my-row"></tr>

</table>

For detailed usage, follow the links in the description above.

对于详细的用法,请按照上面描述的链接进行。

  • See also:
  • Dynamic Components
  • DOM Template Parsing Caveats
  • Source

Built-In Components

component

  • 小工具:
  • is - string | ComponentDefinition | ComponentConstructor
  • inline-template - boolean
  • 用法:

A “meta component” for rendering dynamic components. The actual component to render is determined by the is prop:

用于渲染动态组件的“元组件”。要渲染的实际组件由is prop决定:

<!-- a dynamic component controlled by -->

<!-- the `componentId` property on the vm -->

<component :is="componentId"></component>

<!-- can also render registered component or component passed as prop -->

<component :is="$options.components.child"></component>

  • See also: Dynamic Components
  • Source

transition

  • 小道具:
  • name - string, Used to automatically generate transition CSS class names. 用于自动生成转换CSS类名。e.g. name: \'fade\' will auto expand to .fade-enter.fade-enter-active, etc. Defaults to "v".
  • appear - boolean, Whether to apply transition on initial render. Defaults to false.
  • css - boolean, Whether to apply CSS transition classes. Defaults to true. If set to false, will only trigger JavaScript hooks registered via component events.
  • type - string, Specify the type of transition events to wait for to determine transition end timing. Available values are "transition" and "animation". By default, it will automatically detect the type that has a longer duration.
  • mode - string, Controls the timing sequence of leaving/entering transitions. 控制离开/进入过渡的时间顺序。Available modes are "out-in" and "in-out"; defaults to simultaneous.
  • enter-class - string
  • leave-class - string
  • appear-class - string
  • enter-to-class - string
  • leave-to-class - string
  • appear-to-class - string
  • enter-active-class - string
  • leave-active-class - string
  • appear-active-class - string
  • 事件:
  • before-enter
  • before-leave
  • before-appear
  • enter
  • leave
  • appear
  • after-enter
  • after-leave
  • after-appear
  • enter-cancelled
  • leave-cancelled (v-show only)
  • appear-cancelled
  • 用法:

<transition> serve as transition effects for single element/component. The <transition> only applies the transition behavior to the wrapped content inside; it doesn’t render an extra DOM element, or show up in the inspected component hierarchy.

<transition>作为单个元素/组件的过渡效应。 <transition>仅将过渡行为应用于内部的包装内容; 它不会渲染额外的DOM元素,或显示在被检查的组件层次结构中。

<!-- simple element -->

<transition>

  <div v-if="ok">toggled content</div>

</transition>

<!-- dynamic component -->

<transition name="fade" mode="out-in" appear>

  <component :is="view"></component>

</transition>

<!-- event hooking -->

<div id="transition-demo">

  <transition @after-enter="transitionComplete">

    <div v-show="ok">toggled content</div>

  </transition>

</div>

new Vue({

  ...

  methods: {

    transitionComplete: function (el) {

      // for passed \'el\' that DOM element as the argument, something ...

    }

  }

  ...

}).$mount(\'#transition-demo\')

  • See also: Transitions: Entering, Leaving, and Lists
  • Source

transition-group

  • 小道具:
  • tag - string, defaults to span.
  • move-class - overwrite CSS class applied during moving transition.
  • exposes the same props as <transition> except mode.
  • 事件:
  • exposes the same events as <transition>.
  • 用法:

    • 覆盖在移动转换期间应用的CSS类

<transition-group> serve as transition effects for multiple elements/components. The <transition-group> renders a real DOM element. By default it renders a <span>, and you can configure what element is should render via the tag attribute.

Note every child in a <transition-group> must be uniquely keyed for the animations to work properly.

<transition-group> supports moving transitions via CSS transform. When a child’s position on screen has changed after an updated, it will get applied a moving CSS class (auto generated from the name attribute or configured with the move-class attribute). If the CSS transform property is “transition-able” when the moving class is applied, the element will be smoothly animated to its destination using the FLIP technique.

<transition-group>用作多个元素/组件的过渡效果。 <transition-group>呈现一个真实的DOM元素。默认情况下,它呈现一个<span>,您可以通过tag属性配置要呈现的元素。注意,<transition-group>中的每个孩子都必须是唯一键入,以使动画正常工作。<transition-group>支持通过CSS变换移动转换。当一个孩子在屏幕上的位置更新后,它会被应用一个移动的CSS类(从name属性自动生成或配置了move-class属性)。如果应用移动类时CSS变换属性为“可转换”,则使用FLIP技术将元素平滑地动画到其目的地。

<transition-group tag="ul" name="slide">

  <li v-for="item in items" :key="item.id">

    {{ item.text }}

  </li>

</transition-group>

  • See also: Transitions: Entering, Leaving, and Lists
  • Source

keep-alive

  • 小道具:
  • 用法:

    • include - string or RegExp or Array. Only components matched by this will be cached. 字符串或RegExp或Array。只有与此匹配的组件将被缓存。
    • exclude - string or RegExp or Array. Any component matched by this will not be cached. 字符串或RegExp或Array。只有与此匹配的组件将被缓存。

When wrapped around a dynamic component, <keep-alive> caches the inactive component instances without destroying them. Similar to <transition><keep-alive>is an abstract component: it doesn’t render a DOM element itself, and doesn’t show up in the component parent chain.

When a component is toggled inside <keep-alive>, its activated and deactivatedlifecycle hooks will be invoked accordingly.

In 2.2.0+ and above, activated and deactivated will fire for all nested components inside a <keep-alive> tree.

当缠绕在动态组件上时,<keep-alive>缓存非活动组件实例,而不会破坏它们。与<transition>类似,<keep-alive>是一个抽象组件:它不会呈现DOM元素本身,并且不会显示在组件父链中。当组件在<keep-alive>内切换时,将激活和取消激活的循环钩子。在2.2.0及以上,激活和停用将针对<keep-alive>树中的所有嵌套组件触发。

Primarily used with preserve component state or avoid re-rendering.

主要用于保存组件状态,或避免重新呈现。

<!-- basic -->

<keep-alive>

  <component :is="view"></component>

</keep-alive>

<!-- multiple conditional children -->

<keep-alive>

  <comp-a v-if="a > 1"></comp-a>

  <comp-b v-else></comp-b>

</keep-alive>

<!-- used together with `<transition>` -->

<transition>

  <keep-alive>

    <component :is="view"></component>

  </keep-alive>

</transition>

Note, <keep-alive> is designed for the case where it has one direct child component that is being toggled. It does not work if you have v-for inside it. When there are multiple conditional children, as above, <keep-alive> requires that only one child is rendered at a time.

注意,<keep-alive>是针对具有正在切换的一个直接子组件的情况而设计的。如果你在里面有v-它不起作用当有多个条件儿童时,如上所述,<keep-alive>要求一次只渲染一个孩子节点。

  • include and exclude

New in 2.1.0+

The include and exclude props allow components to be conditionally cached. Both props can be a comma-delimited string, a RegExp or an Array:

include 和exclude 道具允许有条件地缓存组件。两个道具都可以是逗号分隔的字符串,一个RegExp或一个数组:

<!-- comma-delimited string -->

<keep-alive include="a,b">

  <component :is="view"></component>

</keep-alive>

<!-- regex (use `v-bind`) -->

<keep-alive :include="/a|b/">

  <component :is="view"></component>

</keep-alive>

<!-- Array (use `v-bind`) -->

<keep-alive :include="[\'a\', \'b\']">

  <component :is="view"></component>

</keep-alive>

The match is first checked on the component’s own name option, then its local registration name (the key in the parent’s components option) if the name option is not available. Anonymous components cannot be matched against.

<keep-alive> does not work with functional components because they do not have instances to be cached.

匹配首先检查组件的自己的名称选项,然后检查其本地注册名称(父组件选项中的键),如果该名称选项不可用。匿名组件无法匹配。<keep-alive>不适用于功能组件,因为它们没有要缓存的实例。

  • See also: Dynamic Components - keep-alive
  • Source

slot

  • 小道具:
  • name - string, Used for named slot.
  • 用法:

<slot> serve as content distribution outlets in component templates. <slot> itself will be replaced.

For detailed usage, see the guide section linked below.

  • See also: Content Distribution with Slots
  • Source

VNode Interface

  • Please refer to the VNode class declaration.

Server-Side Rendering

  • Please refer to the vue-server-renderer package documentation.

Caught a mistake or want to contribute to the documentation? Edit this page on Github!

以上是 vue.js中英文api 的全部内容, 来源链接: utcz.com/z/376832.html

回到顶部