ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[[官方文档]](https://vuejs.org/v2/api/) ***** 内容目录 [TOC] ***** ## **Global Config** (`Vue.config`) ### `Vue.config.silent` ### `Vue.config.optionMergeStrategies` ### `Vue.config.devtools` ### `Vue.config.errorHandler` ### `Vue.config.warnHandler` ### `Vue.config.ignoredElements` ### `Vue.config.keyCodes` ### `Vue.config.performance` ### `Vue.config.productionTip` ## **Global API** ### `Vue.extend` ### `Vue.nextTick` ### `Vue.set` ### `Vue.delete` ### `Vue.directive` ### `Vue.filter` ### `Vue.component` ### `Vue.use` ### `Vue.mixin` ### `Vue.compile` ### `Vue.version` ## **Options** ### Data #### 1. `Data`, “reactive” data * **Type**: `Object` | `Function` * **Restriction**: Only accepts Function when used in a component definition. * **Details**: 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. 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`. 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. * **Example**: ~~~ javascript 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 } } }) ~~~ #### 2.`props`, accept data from the parent component * **Type**: Array<string> | Object * **Details**: 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 * **Example**: ~~~ javascript // 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 } } } }) ~~~ #### 3. `propsData `, Pass props to an instance during its creation * **Type**: `{ [key: string]: any }` * **Restriction**: only respected in instance creation via `new`. * **Details**: Pass props to an instance during its creation. This is primarily intended to make unit testing easier. * **Example**: ~~~ javascript var Comp = Vue.extend({ props: ['msg'], template: '<div>{{ msg }}</div>' }) var vm = new Comp({ propsData: { msg: 'hello' } }) ~~~ #### 4. `computed`, properties to be mixed into the Vue instance. * **Type**: `{ [key: string]: Function | { get: Function, set: Function } }` * **Details**: 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 if you use an arrow function with a computed property, this won’t be the component’s instance, but you can still access the instance as the function’s first argument: ~~~ javascript computed: { aDouble: vm => vm.a * 2 } ~~~ 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. * **Example**: ~~~ javascript 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 ~~~ #### 5. `methods`, to be mixed into the Vue instance. * **Type**: `{ [key: string]: Function }` * **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. * **Example**: ~~~ javascript var vm = new Vue({ data: { a: 1 }, methods: { plus: function () { this.a++ } } }) vm.plus() vm.a // 2 ~~~ >[danger] 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. #### 6. `watch`, An object where keys are expressions to watch and values are the corresponding callbacks. * **Type**: `{ [key: string]: string | Function | Object | Array}` * **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. * **Example**: ~~~ javascript var vm = new Vue({ data: { a: 1, b: 2, c: 3, d: 4, e: { f: { g: 5 } } }, 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 }, // the callback will be called immediately after the start of the observation d: { handler: function (val, oldVal) { /* ... */ }, immediate: true }, e: [ function handle1 (val, oldVal) { /* ... */ }, function handle2 (val, oldVal) { /* ... */ } ], // watch vm.e.f's value: {g: 5} 'e.f': function (val, oldVal) { /* ... */ } } }) vm.a = 2 // => new: 2, old: 1 ~~~ >[danger] 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. ### DOM #### 1.`el`, a CSS selector string or an actual HTMLElement. * **Type**: string | HTMLElement * **Restriction**: only respected in instance creation via new. * **Details**: Provide the Vue instance an existing DOM element to mount on. It can be a CSS selector string or an actual 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. >[danger] 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>`. >[danger] 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. #### 2. `template`, A string template to be used as the markup for the Vue instance. * **Type**: string * **Details**: A string template to be used as the markup for the Vue instance. The template will replace the mounted element. Any existing markup inside the mounted element will be ignored, unless content distribution slots are present in the template. 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. >[danger] From a security perspective, you should only use Vue templates that you can trust. Never use user-generated content as your template. >[danger] If render function is present in the Vue option, the template will be ignored. #### 3. `render`,receives a `createElement` method as it’s first argument used to create `VNodes`. * **Type**: `(createElement: () => VNode) => VNode` * **Details**: 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`. 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. >[danger] 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. #### 4. `renderError`,Only works in development mode. * **Type**: `(createElement: () => VNode, error: Error) => VNode` * **Details**: 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. * **Example**: ~~~ javascript new Vue({ render (h) { throw new Error('oops') }, renderError (h, err) { return h('pre', { style: { color: 'red' }}, err.stack) } }).$mount('#app') ~~~ ### Lifecycle Hooks (functions) >[danger] 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. #### 1. `beforeCreate`, after the instance has been initialized, before data observation and event/watcher setup. Called synchronously immediately after the instance has been initialized, before data observation and event/watcher setup. #### 2. `created`, after the instance is created. 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. #### 3. `beforeMount`, before the mounting begins. Called right before the mounting begins: the `render` function is about to be called for the first time. **This hook is not called during server-side rendering.** #### 4. `mounted`, after the instance has been mounted. 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`: ~~~ javasccript 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.** #### 5. `beforeUpdate`, when data changes, before the DOM is patched. Called when data changes, before the DOM is patched. This is a good place to access the existing DOM before an update, e.g. to remove manually added event listeners. **This hook is not called during server-side rendering, because only the initial render is performed server-side.** #### 6. `updated`, after a data change causes the virtual DOM to be re-rendered and patched. Called after a data change causes the virtual DOM to be re-rendered and patched. 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. 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`: ~~~ javascript updated: function () { this.$nextTick(function () { // Code that will run only after the // entire view has been re-rendered }) } ~~~ #### 7. `activated`, a kept-alive component is activated. Called when a kept-alive component is activated. **This hook is not called during server-side rendering.** #### 8. `deactivated`, a kept-alive component is deactivated. Called when a kept-alive component is deactivated. **This hook is not called during server-side rendering.** #### 9. `beforeDestroy`, before a Vue instance is destroyed. Called right before a Vue instance is destroyed. At this stage the instance is still fully functional. **This hook is not called during server-side rendering.** #### 10. `destroyed`, after a Vue instance has been destroyed. 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. **This hook is not called during server-side rendering.** #### 11. `errorCaptured`, an error from any descendent component is captured. Called when an error from any descendent component is captured. The hook receives three arguments: * the error, * the component instance that triggered the error, and * a string containing information on where the error was captured. The hook can return `false` to stop the error from propagating further. >[danger] You can modify component state in this hook. However, it is important to have conditionals in your template or render function that short circuits other content when an error has been captured; otherwise the component will be thrown into an infinite render loop. **Error Propagation Rules** * By default, all errors are still sent to the global config.errorHandler if it is defined, so that these errors can still be reported to an analytics service in a single place. * If multiple errorCaptured hooks exist on a component’s inheritance chain or parent chain, all of them will be invoked on the same error. * If the errorCaptured hook itself throws an error, both this error and the original captured error are sent to the global config.errorHandler. * An errorCaptured hook can return false to prevent the error from propagating further. This is essentially saying “this error has been handled and should be ignored.” It will prevent any additional errorCaptured hooks or the global config.errorHandler from being invoked for this error. ### Assets #### 1.`directives` * **Type**: `Object` * **Details**: A hash of directives to be made available to the Vue instance. #### 2.`filters` * **Type**: `Object` * **Details**: A hash of filters to be made available to the Vue instance. #### 3.`components` * **Type**: `Object` * **Details**: A hash of components to be made available to the Vue instance. ### Composition #### 1. `parent` #### 2. `mixins` #### 3. `extends` #### 4. `provide / inject` ### Misc #### 1. `name` #### 2.`delimiters` #### 3. `functional` #### 4. `model` #### 5. `inheritAttrs` #### 6. `comments` ## **Instance** ### Properties #### 1. ` vm.$data` #### 2. ` vm.$props` #### 3. ` vm.$el` #### 4. `vm.$options` #### 5. `vm.$parent` #### 6. `vm.$root` #### 7. ` vm.$children` #### 8. `vm.$slots` #### 9. `vm.$scopedSlots` #### 10. `vm.$refs` #### 11. ` vm.$isServer` #### 12. `vm.$attrs` #### 13. `vm.$listeners` ### Methods/Data #### 1. `vm.$watch` #### 2. `vm.$set` #### 3. `vm.$delete` ### Methods/Events #### 1. ` vm.$on` #### 2. `vm.$once` #### 3. `vm.$off` #### 4. `vm.$emit` ### Methods/Lifecycle #### 1. `vm.$mount` #### 2. `vm.$forceUpdate` #### 3. `vm.$nextTick` #### 4. `vm.$destroy` ## **Directives** ### 1. `v-text` * **Expects**: string * **Details**: Updates the element’s `textContent`. If you need to update the part of textContent, you should use `{{ Mustache }} `interpolations. * **Example**: ~~~ html <span v-text="msg"></span> <!-- same as --> <span>{{msg}}</span> ~~~ ### `v-html` ### `v-show` ### `v-if` ### `v-else` ### `v-else-if` ### `v-for` ### `v-on` ### `v-bind` ### `v-model` ### `v-pre` ### `v-cloak` ### `v-once` ## Special Attributes ### `key` ### `ref` ### `slot` ### `slot-scope` ### `is` ## Built-In Components ### `component` ### `transition` ### `transition-group` ### `keep-alive` ### `slot` ## VNode Interface [【官方文档】](https://github.com/vuejs/vue/blob/dev/src/core/vdom/vnode.js) ## Server-Side Rendering [【官方文档】](https://github.com/vuejs/vue/tree/dev/packages/vue-server-renderer)