Vue 2 Docs

Posted on  by admin

The jsPlumb Toolkit has several components to assist you in integrating with Vue 2.

Lifecycle Diagram

These are shipped in the package @jsplumbtoolkit/browser-ui-vue2. There is a demonstration on Github that you can clone to get started, or just browse through the code:.

Data and Methods

  • We'll refer to this demonstration occasionally in this document.

  • The Toolkit's Vue2 components are shipped with precompiled templates, meaning you need to import the Toolkit in your Vue bootstrap code.

  • For instance, this is the bootstrap routine from the Flowchart demonstration: .

    The Toolkit offers 2 components and 3 mixins:.

Rendering Nodes and Groups#

  • This component provides an instance of the Toolkit and a surface widget to render the contents.

  • All attributes are optional.

  • Note that Vue prefers "kebab case" for attribute names, even if the actual property is camel case on the component (and of course Javascript does not like kebab case for property names).

    id Unique ID for the Toolkit instance.

    Can be used to retrieve a Toolkit instance from the jsPlumbToolkitVue2 module. surface-id Unique ID for the Surface widget. Required if you wish to attach a Miniview or a Palette.

  • Also useful if you wish to interact with a Surface, to perform operations such as zooming, centering on content, etc.

Components#

  • render-params Parameters to pass in to the constructor of the Surface widget.

  • Note here we use the v-bind: prefix to tell Vue that the object weare injecting is in the Vue instance's model.

  • toolkit-params Parameters to pass in to the constructor of the Toolkit instance.

    Note again the use of v-bind: in our example above. view View parameters. Views are discussed here. This is a component that provides a miniview that can be attached to some surface. surface-id ID for the surface widget to which to attach the Miniview.

Instance Lifecycle Hooks

  • This mixin is a wrapper around the Drop Manager, which offers the ability to drop onto edges, nodes and the canvas itself.

  • This mixin is supplied in a separate package, as it has a dependency on the Toolkit's underlying Drop Manager.

  • This is an example of a component that uses the SurfaceDrop mixin.

    We show, in the onCanvasDrop method, an example of how this mixin can be used to replace the previous Palette mixin.

    Note, though, the onEdgeDrop and onDrop methods: these are, respectively, called when an element is dragged on an Edge or a Node/Group. Note that this component itself doesn't declare any props, and you are free to provide any template you wish torender the component's data.

    The underlying DragDrop mixin's props are:. surfaceId:string Required.

    The ID of the Surface to which to attach the Drop Manager. selector:string Required. A CSS3 selector instructing the Toolkit how to identify which elements in the component represent draggable node types.

    dataGenerator:(el:HTMLElement) => T Optional. A function that can return a data object representing an element which is being dragged.

Rendering Ports#

This function is called as soon as an element starts to be dragged.

  • allowDropOnGroup:boolean Optional, defaults to true.

  • If true, then elements can be dropped onto nodes/groups, and in the event that occurs, the onDrop method will be called.

  • allowDropOnCanvas:boolean Optional, defaults to true.

    When an element is dropped on the canvas whitespace, it is added to the dataset and rendered. allowDropOnEdge:boolean Optional, defaults to true.

# Tech stack

  • If true, then elements can be dropped onto edges, and in the event that an element is dropped on an edge, a new node/group is added and inserted between the sourceand target of the original edge, and the original edge is discarded..

  • typeGenerator:(data:T) => string Optional.

  • A function that can return the correct type for some data object representing an element being dragged.

    By default the Toolkit will use the type member of the data object. groupIdentifier:(d: T, el: HTMLElement) => boolean Optional. By default, the toolkit looks for a jtk-is-group attribute on an element being dragged.

Declarative Rendering

  • If found,with a value of "true", then the Toolkit assumes a group is being dragged.

  • You can supply your own function to make this decision.

  • This mixin should be included in any component you will use to render a node (see below for discussion of this).Several helper methods are exposed by this mixin:.

    getNode() Gets the underlying Toolkit node that the component is rendering.

# What's next?

removeNode() Instructs the Toolkit to remove the node that the component is rendering.

  • This will of course result in the destruction of the component.

  • getToolkit() Gets the underlying Toolkit instance for the node the component is rendering.

  • updateNode(data:any) Updates the underlying node that the component is rendering.

    Nodes rendered with this mixin are fully reactive: calls to updateNode will result in a repaint of the componentwith no further effort involved on your part. This mixin should be included in any component you will use to render a group (see below for discussion of this).

Ready for More?

Several helper methods are exposed by this mixin:.

  • getGroup() Gets the underlying Toolkit group that the component is rendering.

  • removeGroup(removeChildNodes?:boolean) Instructs the Toolkit to remove the group that the component is rendering, and possibly all of the child nodes of the group too.

  • This will of course result in the destruction of the component.

    getToolkit() Gets the underlying Toolkit instance for the group the component is rendering.

Getting Started

Handling User Input

  • updateGroup(data:any) Updates the underlying group that the component is rendering.

    • {Object} options
  • Groups rendered with this mixin are fully reactive: calls to updateGroup will result in a repaint of the component with no further effort involved on your part.

    To render nodes and groups you need to do 3 things:. create a component. import it into the code that's handling your Toolkit instance.

    map it via the view. Imagine you make this component inside MyNode.vue:. And you make this component, to manage an instance of the Toolkit:.

    MyNode is mapped to the component used to render nodes of type "default" (which for the Toolkit means any node).

  • The jsplumb-toolkit declaration in the template is the one from the Flowchart Builder, which is a good place to look to get a feel for how a whole application can be built using the Toolkit.

Imports#

  • The Vue2 integration supports rendering ports, but we have not yet created a demonstration such as this Angular demonstration that shows the code in action.

    • {Function} [callback]
    • {Object} [context]
  • Watch this space.

    #TechForUkraine - We oppose Russia's unprovoked and unjustified attack on Ukraine. Russia launched a devastating, unprovoked, and unjustified attack on Ukraine.

    Ukraine and its people need help - if you are unable to help locally, by sheltering a fellow Ukrainian, you can also:. Support the Ukraine Armed forces directly by sending funding to NBU Special Account(opens new window). Help the Ukrainian Red Cross Society(opens new window).

  • Donate to United Help Ukraine(opens new window).

Conditionals and Loops

  • Donate to Voices of Children(opens new window).

    • {Object | Array} target
    • {string | number} propertyName/index
    • {any} value
  • Vue Storefront is a e-commerce frontend framework based on Nuxt.js(opens new window) that can work with any e-commerce backend API.

  • Additionally, thanks to low coupling and high cohesion, it can connect to other services, giving you the freedom to work with the technologies you know and love, be it CMS, ERP, PIM, or anything else.

    With Vue Storefront, you're getting a performant frontend connected to headless e-commerce, CMS, and other third-party platforms of your choice, along with hundreds of ready-to-use Vue Storefront and Nuxt.js modules for all standard functionalities.

    Thanks to them, you will save hundreds (or even thousands) of working hours, so you can focus on creating value for your product while leaving the heavy lifting to us!

  • By some estimates, up to 1% of users will leave your website for every 100ms of delay in page load time.

Setup#

  • With Vue Storefront, you can create a performant shop thanks to:.

    • {Object | Array} target
    • {string | number} propertyName/index

    using modern technologies for small bundle sizes and performance;.

  • using code splitting, lazy loading, and lazy hydration to only load what's needed at the moment;.

    caching the resources, so the already visited pages are loaded instantly;. preloading resources that might be needed in the future;. hosting and executing as much as possible on the server, so the part served to the users is much lighter and faster compared to traditional SPA;.

    Our list of supported and planned integrations on the Integrations page gets longer every month.

  • Additionally, there are hundreds of Nuxt modules you can use.

# Features

  • You can browse them on the Nuxt Modules(opens new window) website and Awesome Nuxt(opens new window) repository.

    • {string} id
    • {Function | Object} [definition]
  • The speed and flexibility of Vue Storefront wouldn't be possible without the great technologies that power it:.

    SCSS(opens new window) (optional).

  • Storefront UI(opens new window) (optional).

Composing with Components

  • TypeScript(opens new window) (optional).

    • {string} id
    • {Function} [definition]
  • Cypress(opens new window) (optional).

    If you're already convinced to use Vue Storefront, check the Installation guide.

  • If you want to learn more, check out the Introduction to Vue Storefront.

What is Vue.js?

  • In addition to SVG framework, Iconify offers native components for several popular UI frameworks.

    • {string} id
    • {Function | Object} [definition]
  • Iconify for Vue is one of such components.

    Yet another icon component? What are advantages over other icon components? One syntax for over 100,000 icons from 100+ icon sets.

  • Many components simply render icon fonts, which look ugly.

Creating a Vue Instance

  • Iconify renders pixel perfect SVG.

    • {Object | Function} plugin
  • Loads icons on demand.

    No need to bundle icons, component will automatically load icon data for icons that you use from Iconify API. This documentation is for Vue component for Vue 2. If you are using Vue 3, see documentation for Vue 3 component.

    If you are using NPM:. If you are using Yarn:. Install @iconify/vue2 and import component from it (component is exported as named export):.

    Then in template use Icon component with icon name as icon parameter:. Retrieving icon data from Iconify API requires visitor to be online.

  • What if you want to use component offline or on local network?

BaseGroupComponent#

  • There are several options:.

    • {Object} mixin
  • You can build icon bundles for icons that are used in your application, making icon data available offline.

    You can use individual icon packages, which is similar to icon bundles, but import icons one by one and are easier to use. See icon bundles for Iconify for Vue 2 documentation.

  • Component is compatible with Nuxt.js.

jsplumb-toolkit#

  • Component does not retrieve icon data until it is mounted.

    • {string} template
  • For server side rendering it means HTML will not include SVGs, they will be dynamically added only when hydrating DOM on client side.

    If you do want to render SVGs on server side, use either offline bundle or provide icon data as parameter instead of icon name.

  • If you want to use icon component's functions that load icon data from API in Nuxt.js, you need Fetch API.

# Lightning-fast online shop

Currently Node.js does not natively support Fetch API.

  • It is available in Node.js version 17 using flag "--experimental-fetch", but without it Fetch API is not available.

    • {Object} object
  • That means icon component cannot retrieve icon data from Iconify API when used on a server side in Node.js environment.

    How to support API in server side rendering? Install cross-fetch (if you are using CommonJS) or node-fetch (if you are using modules) as dependency.

    Use internal setFetch() function to set third party Fetch API before using any icon component functions. This code must be added only to script that runs on server side, not bundled for client side use.

    Browsers already support Fetch API, so this code is not needed in browsers. You can pass any custom properties to component. Required properties:. icon, IconifyIcon | string icon name or icon data. Optional properties:. inline, boolean toggles inline or block mode. width, string | number icon width. height, string | number icon height. horizontalFlip, boolean flips icon horizontally.

  • verticalFlip, boolean flips icon vertically.

Bootstrap#

  • flip, string alternative to horizontalFlip and verticalFlip. rotate, number | string rotates icon. color, string changes icon color. horizontalAlign horizontally aligns content inside icon.

  • verticalAlign vertically aligns content inside icon.

# Extensibility

# Short time to market

  • slice alignment behaviour: "meet" or "slice".

  • align, string aligns content inside icon, alternative to horizontalAlign, verticalAlign and slice.

  • onLoad, function is a callback that is called when icon data has been loaded.

    See below for more information on each optional property. In addition to the properties mentioned above, the icon component accepts any other properties and events. All other properties and events will be passed to generated SVG element, so you can do stuff like setting the inline style, add title, add onClick event and so on.

    Icon name is a string, which has 3 parts:. provider points to API source. Starts with "@", can be empty (empty value is used for public Iconify API). prefix is name of icon set.

    name is name of icon. Examples of valid icon names:. flat-color-icons:voice-presentation - icon is "voice-presentation" from Flat Color Icons icon set, from public Iconify API. mdi-light:home - icon is "home" from Material Design Light icon set, from public Iconify API.

    If API provider is empty, it can be skipped (like in examples above). If prefix does not contain "-", prefix and icon name can be separated with dash. This is to support people migrating from icon fonts. For example, fa:arrow-left and fa-arrow-left are identical because "fa" does not contain dash.

    There are over 100,000 icons available from 100+ icon sets. Browse icons sets to see all available icons. You can also add custom API providers for more icon choices. See API providers documentation. You can only change color of monotone icons. Some icons, such as emoji, have a hardcoded palette that cannot be changed. To add color to a monotone icon simply change text color. For various ways to set color, see how to change icon color in Iconify for Vue.

    By default, icon height is set to "1em", icon width is changed dynamically based on the icon's width to height ratio. This makes it easy to change icon size by changing font-size in the stylesheet, just like icon fonts.

  • There are several ways to change icon dimensions:.

    Setting font-size in style (or fontSize if you are using inline style). Setting width and/or height property. Values for width and height can be numbers or strings. If you set only one dimension, another dimension will be calculated using the icon's width to height ratio.

  • For example, if the icon size is 16 x 24, you set the height to 48, the width will be set to 32.

BaseNodeComponent#

  • Calculations work not only with numbers, but also with string values.

  • For various ways to change icon dimensions and alignment, see how to change icon dimensions in Iconify for Vue.

    An icon can be rotated and flipped horizontally and/or vertically. All transformations are done relative to the center of the icon. These are not CSS transformations, transformations are applied inside SVG.

    For more details see how to transform icon in Iconify for Vue.

    • onLoad property is an optional callback function. It is called when icon data has been loaded. It is not an event, such as click event for links, it is a simple callback function. When onLoad is called:. If value of icon property is an object, onLoad is not called. If value of icon property is a string and icon data is available, onLoad is called on first render. If value of icon property is a string and icon data is not available, onLoad is called on first re-render after icon data is retrieved from API.
    • What is the purpose of onLoad? To let you know when Icon component renders an icon and when it does not render anything. This allows you to do things like adding class name for parent element, such as "container--with-icon" that modify layout if icon is being displayed.
    • Component exports various functions, which developers can use to control icons. Functions are split in several groups (click function name to see more details and examples):. There are several functions in this section:.
    • iconExists(name). Checks if an icon exists, returns boolean. Lists available icons, returns string[]. Returns icon data, returns IconifyIcon object. Functions for adding icons to component:. addCollection(). Adds an icon set. Note: icons added to component with these functions are not stored in cache.
  • Component caches only icons retrieved from API.

  • replaceIDs(html).

SurfaceDrop mixin#

  • Randomizes IDs in generated string. This should be used when rendering icon based on data returned by getIcon() to make sure elements inside each icon have unique IDs.

  • calculateSize(). Calculates icon size. It is used to calculate width if only height is set and vice versa.

  • buildIcon(icon, customisations?).

    Generates data used by icon component. This can be used if you prefer to generate yourself.

  • Data includes attributes for and inner HTML.

jsplumb-miniview#

  • loadIcons(icons, callback?). Loads icons from API, calls optional callback when either all or part of icons have been loaded.

  • loadIcon(icon).

    Loads one icon from API, returns Promise. Enables caching in localStorage and sessionStorage. disableCache(). Disables caching in localStorage and sessionStorage.

    addAPIProvider(). Adds custom API provider. See API providers documentation. There are several internal API functions that are exposed. They are intended to be used by developers that need more control over component.

    For example, it is used in Iconify Icon Finder. Use them carefully. All internal API functions are exposed as properties of _api object:. Returns internal API module. getAPIConfig().

  • Returns API configuration.

  • setAPIModule(provider).

Relation to Custom Elements

  • Sets API module for provider. This is experimental function intended for custom API providers that use custom module for retrieving data from API.

  • setFetch(fetch).

    Set custom Fetch API. Returns used fetch() function, null if Fetch API is not available. You’re browsing the documentation for v2.x and earlier. For v3.x, click here. Every Vue application starts by creating a new Vue instance with the Vue function:.

    Although not strictly associated with the MVVM pattern, Vue’s design was partly inspired by it. As a convention, we often use the variable vm (short for ViewModel) to refer to our Vue instance. When you create a Vue instance, you pass in an options object.

  • The majority of this guide describes how you can use these options to create your desired behavior.

  • For reference, you can also browse the full list of options in the API reference.

watch

  • A Vue application consists of a root Vue instance created with new Vue, optionally organized into a tree of nested, reusable components.

  • For example, a todo app’s component tree might look like this:.

    We’ll talk about the component system in detail later. For now, just know that all Vue components are also Vue instances, and so accept the same options object (except for a few root-specific options). When a Vue instance is created, it adds all the properties found in its data object to Vue’s reactivity system.

  • When the values of those properties change, the view will “react”, updating to match the new values.

    When this data changes, the view will re-render. It should be noted that properties in data are only reactive if they existed when the instance was created. That means if you add a new property, like:. Then changes to b will not trigger any view updates. If you know you’ll need a property later, but it starts out empty or non-existent, you’ll need to set some initial value.

  • The only exception to this being the use of Object.freeze(), which prevents existing properties from being changed, which also means the reactivity system can’t track changes.

Options / DOM

el

  • In addition to data properties, Vue instances expose a number of useful instance properties and methods.

  • These are prefixed with $ to differentiate them from user-defined properties.

  • In the future, you can consult the API reference for a full list of instance properties and methods.

    Each Vue instance goes through a series of initialization steps when it’s created - for example, it needs to set up data observation, compile the template, mount the instance to the DOM, and update the DOM when data changes.

    Along the way, it also runs functions called lifecycle hooks, giving users the opportunity to add their own code at specific stages.

    For example, the created hook can be used to run code after an instance is created:. There are also other hooks which will be called at different stages of the instance’s lifecycle, such as mounted, updated, and destroyed.

    All lifecycle hooks are called with their this context pointing to the Vue instance invoking it. Don’t use arrow functions on an options property or callback, such as created: () => console.log(this.a) or vm.$watch('a', newValue => this.myMethod()).

    Since an arrow function doesn’t have a this, this will be treated as any other variable and lexically looked up through parent scopes until found, often resulting in errors such as Uncaught TypeError: Cannot read property of undefined or Uncaught TypeError: this.myMethod is not a function.

  • Below is a diagram for the instance lifecycle.

template

  • You don’t need to fully understand everything going on right now, but as you learn and build more, it will be a useful reference.

  • Caught a mistake or want to contribute to the documentation?Edit this on GitHub!Deployed onNetlify .

    You’re browsing the documentation for v2.x and earlier. For v3.x, click here. Vue (pronounced /vjuː/, like view) is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable.

    The core library is focused on the view layer only, and is easy to pick up and integrate with other libraries or existing projects. On the other hand, Vue is also perfectly capable of powering sophisticated Single-Page Applications when used in combination with modern tooling and supporting libraries.

    If you’d like to learn more about Vue before diving in, we created a video walking through the core principles and a sample project.

    If you are an experienced frontend developer and want to know how Vue compares to other libraries/frameworks, check out the Comparison with Other Frameworks.

  • The official guide assumes intermediate level knowledge of HTML, CSS, and JavaScript.

render

  • If you are totally new to frontend development, it might not be the best idea to jump right into a framework as your first step - grasp the basics then come back!

  • Prior experience with other frameworks helps, but is not required.

    The easiest way to try out Vue.js is using the Hello World example. Feel free to open it in another tab and follow along as we go through some basic examples. Or, you can create an index.html file and include Vue with:.

    The Installation page provides more options of installing Vue. Note: We do not recommend that beginners start with vue-cli, especially if you are not yet familiar with Node.js-based build tools.

    If you prefer something more interactive, you can also check out this tutorial series on Scrimba, which gives you a mix of screencast and code playground that you can pause and play around with anytime.

  • At the core of Vue.js is a system that enables us to declaratively render data to the DOM using straightforward template syntax:.

renderError

We have already created our very first Vue app!

  • This looks pretty similar to rendering a string template, but Vue has done a lot of work under the hood.

  • The data and the DOM are now linked, and everything is now reactive.

    How do we know? Open your browser’s JavaScript console (right now, on this page) and set app.message to a different value.

    You should see the rendered example above update accordingly. Note that we no longer have to interact with the HTML directly. A Vue app attaches itself to a single DOM element (#app in our case) then fully controls it.

  • The HTML is our entry point, but everything else happens within the newly created Vue instance.

  • In addition to text interpolation, we can also bind element attributes like this:.

Options / Lifecycle Hooks

Hover your mouse over me for a few seconds to see my dynamically bound title! Here we are encountering something new. The v-bind attribute you are seeing is called a directive. Directives are prefixed with v- to indicate that they are special attributes provided by Vue, and as you may have guessed, they apply special reactive behavior to the rendered DOM. Here, it is basically saying “keep this element’s title attribute up-to-date with the message property on the Vue instance.”.

beforeCreate

  • If you open up your JavaScript console again and enter app2.message = 'some new message', you’ll once again see that the bound HTML - in this case the title attribute - has been updated.

  • It’s easy to toggle the presence of an element, too:.

    Go ahead and enter app3.seen = false in the console. You should see the message disappear. This example demonstrates that we can bind data to not only text and attributes, but also the structure of the DOM.

  • Moreover, Vue also provides a powerful transition effect system that can automatically apply transition effects when elements are inserted/updated/removed by Vue.

created

  • There are quite a few other directives, each with its own special functionality.

  • For example, the v-for directive can be used for displaying a list of items using the data from an Array:.

    In the console, enter app4.todos.push({ text: 'New item' }). You should see a new item appended to the list. To let users interact with your app, we can use the v-on directive to attach event listeners that invoke methods on our Vue instances:. Note that in this method we update the state of our app without touching the DOM - all DOM manipulations are handled by Vue, and the code you write is focused on the underlying logic.

  • Vue also provides the v-model directive that makes two-way binding between form input and app state a breeze:.

beforeMount

  • The component system is another important concept in Vue, because it’s an abstraction that allows us to build large-scale applications composed of small, self-contained, and often reusable components.

  • If we think about it, almost any type of application interface can be abstracted into a tree of components:.

    In Vue, a component is essentially a Vue instance with pre-defined options. Registering a component in Vue is straightforward:.

    Now you can compose it in another component’s template:.

  • But this would render the same text for every todo, which is not super interesting.

mounted

  • We should be able to pass data from the parent scope into child components.

  • Let’s modify the component definition to make it accept a prop:.

    Now we can pass the todo into each repeated component using v-bind:. This is a contrived example, but we have managed to separate our app into two smaller units, and the child is reasonably well-decoupled from the parent via the props interface.

    We can now further improve our component with more complex template and logic without affecting the parent app. In a large application, it is necessary to divide the whole app into components to make development manageable.

    We will talk a lot more about components later in the guide, but here’s an (imaginary) example of what an app’s template might look like with components:.

  • You may have noticed that Vue components are very similar to Custom Elements, which are part of the Web Components Spec.

beforeUpdate

  • That’s because Vue’s component syntax is loosely modeled after the spec.

  • For example, Vue components implement the Slot API and the is special attribute.

    However, there are a few key differences:. The Web Components Spec has been finalized, but is not natively implemented in every browser.

    Safari 10.1+, Chrome 54+ and Firefox 63+ natively support web components. In comparison, Vue components don’t require any polyfills and work consistently in all supported browsers (IE9 and above).

  • When needed, Vue components can also be wrapped inside a native custom element.

updated

  • Vue components provide important features that are not available in plain custom elements, most notably cross-component data flow, custom event communication and build tool integrations.

  • Although Vue doesn’t use custom elements internally, it has great interoperability when it comes to consuming or distributing as custom elements.

    Vue CLI also supports building Vue components that register themselves as native custom elements.

    We’ve briefly introduced the most basic features of Vue.js core - the rest of this guide will cover them and other advanced features with much finer details, so make sure to read through it all! Video by Vue Mastery. Watch Vue Mastery’s free Intro to Vue course.

    ← InstallationThe Vue Instance →.

    Caught a mistake or want to contribute to the documentation?Edit this on GitHub!Deployed onNetlify .

  • See also:Lifecycle Diagram

activated

  • Type:Function

  • Details:

    Called when a kept-alive component is activated.

    This hook is not called during server-side rendering.

  • See also:

deactivated

  • Type:Function

  • Details:

    Called when a kept-alive component is deactivated.

    This hook is not called during server-side rendering.

  • See also:

beforeDestroy

  • Type:Function

  • Details:

    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.

  • See also:Lifecycle Diagram

destroyed

  • Type:Function

  • Details:

    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.

  • See also:Lifecycle Diagram

errorCaptured

New in 2.5.0+

  • Type:(err: Error, vm: Component, info: string) => ?boolean

  • Details:

    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.

    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.

Options / Assets

directives

  • Type:Object

  • Details:

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

  • See also:Custom Directives

filters

  • Type:Object

  • Details:

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

  • See also:Vue.filter

components

  • Type:Object

  • Details:

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

  • See also:Components

Options / Composition

parent

  • Type:Vue instance

  • Details:

    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.

mixins

  • Type:Array

  • Details:

    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.

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

  • Example:

  • See also:Mixins

  • extends

    • Type:Object | Function

    • Details:

      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.

    • Example:

    provide / inject

    New in 2.2.0+

    • Type:

      • provide:Object | () => Object
      • inject:Array | { [key: string]: string | Symbol | Object }
    • Details:

      This pair of options are used together to allow an ancestor component to serve as a dependency injector for all its 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.

      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.

      The inject option should be either:

      • an array of strings, or
      • an object where the keys are the local binding name and the value is either:
        • the key (string or Symbol) to search for in available injections, or
        • an object where:
          • the from property is the key (string or Symbol) to search for in available injections, and
          • the default property is used as fallback value

      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.

    • Example:

      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.

      Using an injected value as the default for a prop:

      Using an injected value as data entry:

      In 2.5.0+ injections can be optional with default value:

      If it needs to be injected from a property with a different name, use from to denote the source property:

      Similar to prop defaults, you need to use a factory function for non primitive values:

    Options / Misc

    name

    • Type:string

    • Restriction: only respected when used as a component option.

    • Details:

      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.

      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 , which isn’t very informative. By providing the name option, you will get a much more informative component tree.

    delimiters

    • Type:Array

    • Default:["{{", "}}"]

    • Restrictions: This option is only available in the full build, with in-browser compilation.

    • Details:

      Change the plain text interpolation delimiters.

    • Example:

    functional

    • Type:boolean

    • Details:

      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

    model

    New in 2.2.0

    • Type:{ prop?: string, event?: string }

    • Details:

      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.

    • Example:

      The above will be equivalent to:

    inheritAttrs

    New in 2.4.0+

    • Type:boolean

    • Default:true

    • Details:

      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 $attrs instance 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.

    New in 2.4.0+

    • Type:boolean

    • Default:false

    • Restrictions: This option is only available in the full build, with in-browser compilation.

    • Details:

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

    Instance Properties

    vm.$data

    • Type:Object

    • Details:

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

    • See also:Options / Data - data

    vm.$props

    New in 2.2.0+

    • Type:Object

    • Details:

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

    vm.$el

    • Type:Element

    • Read only

    • Details:

      The root DOM element that the Vue instance is managing.

    vm.$options

    • Type:Object

    • Read only

    • Details:

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

    vm.$parent

    • Type:Vue instance

    • Read only

    • Details:

      The parent instance, if the current instance has one.

    vm.$root

    • Type:Vue instance

    • Read only

    • Details:

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

    vm.$children

    • Type:Array

    • Read only

    • Details:

      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.

    vm.$slots

    • Type:{ [name: string]: ?Array }

    • Read only

    • Reactive? No

    • Details:

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

      Please note that slots are not reactive. If you need a component to re-render based on changes to data passed to a slot, we suggest considering a different strategy that relies on a reactive instance option, such as props or data.

      Note:v-slot:foo is supported in v2.6+. For older versions, you can use the deprecated syntax.

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

    • Example:

    • See also:

    vm.$scopedSlots

    New in 2.1.0+

    • Type:{ [name: string]: props => Array | undefined }

    • Read only

    • Details:

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

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

      Note: since 2.6.0+, there are two notable changes to this property:

      1. Scoped slot functions are now guaranteed to return an array of VNodes, unless the return value is invalid, in which case the function will return undefined.

      2. All $slots are now also exposed on $scopedSlots as functions. If you work with render functions, it is now recommended to always access slots via $scopedSlots, whether they currently use a scope or not. This will not only make future refactors to add a scope simpler, but also ease your eventual migration to Vue 3, where all slots will be functions.

    • See also:

    vm.$refs

    • Type:Object

    • Read only

    • Details:

      An object of DOM elements and component instances, registered with ref attributes.

    • See also:

    vm.$isServer

    • Type:boolean

    • Read only

    • Details:

      Whether the current Vue instance is running on the server.

    • See also:Server-Side Rendering

    vm.$attrs

    New in 2.4.0+

    • Type:{ [key: string]: string }

    • Read only

    • Details:

      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.

    vm.$listeners

    New in 2.4.0+

    • Type:{ [key: string]: Function | Array }

    • Read only

    • Details:

      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 transparent wrapper components.

    Instance Methods / Data

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

    • Arguments:

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

    • Usage:

      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.

    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.

    • Example:

      vm.$watch returns an unwatch function that stops firing the callback:

    • Option: deep

      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.

    • Option: immediate

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

      Note that with immediate option you won’t be able to unwatch the given property on the first callback call.

      If you still want to call an unwatch function inside the callback, you should check its availability first:

    vm.$set( target, propertyName/index, value )

    • Arguments:

      • {Object | Array} target
      • {string | number} propertyName/index
      • {any} value
    • Returns: the set value.

    • Usage:

      This is the alias of the global Vue.set.

    • See also:Vue.set

    vm.$delete( target, propertyName/index )

    • Arguments:

      • {Object | Array} target
      • {string | number} propertyName/index
    • Usage:

      This is the alias of the global Vue.delete.

    • See also:Vue.delete

    Instance Methods / Events

    vm.$on( event, callback )

    • Arguments:

      • {string | Array} event (array only supported in 2.2.0+)
      • {Function} callback
    • Usage:

      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.

    • Example:

    vm.$once( event, callback )

    • Arguments:

      • {string} event
      • {Function} callback
    • Usage:

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

    vm.$off( [event, callback] )

    • Arguments:

      • {string | Array} event (array only supported in 2.2.2+)
      • {Function} [callback]
    • Usage:

      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.

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

    • Arguments:

      • {string} eventName
      • [...args]

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

    • Examples:

      Using $emit with only an event name:

      Using $emit with additional arguments:

    Instance Methods / Lifecycle

    vm.$mount( [elementOrSelector] )

    • Arguments:

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

    • Usage:

      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.

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

    • Example:

    • See also:

    vm.$forceUpdate()

    • Usage:

      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.

    vm.$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. 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.

      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.

    • Example:

    • See also:

    vm.$destroy()

    • Usage:

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

      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.

      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.

    • Example:

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

    • See also:

    v-bind

    • Shorthand::

    • Expects:any (with argument) | Object (without argument)

    • Argument:attrOrProp (optional)

    • Modifiers:

      • .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.
    • Usage:

      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.

    • Example:

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

      .camel is not needed if you are using string templates, or compiling with vue-loader/vueify.

    • See also:

    v-model

    • Expects: varies based on value of form inputs element or output of components

    • Limited to: