Conditional rendering

Why Listeners in HTML?

You might be concerned that this whole event listening approach violates the good old rules about “separation of concerns”. Rest assured — since all Vue handler functions and expressions are strictly bound to the ViewModel that’s handling the current view, it won’t cause any maintenance difficulty. In fact, there are several benefits in using :

  1. It’s easier to locate the handler function implementations within your JS code by skimming the HTML template.

  2. Since you don’t have to manually attach event listeners in JS, your ViewModel code can be pure logic and DOM-free. This makes it easier to test.

  3. When a ViewModel is destroyed, all event listeners are automatically removed. You don’t need to worry about cleaning it up yourself.

##company## — ##description##

Edit this on GitHub! Netlify


Репозитарий: v-click-outsideДемо: здесьУстановка: 

Что если вам понадобиться закрыть компонент, при клике снаружи компонента? Это можно сделать в одно мгновение с помощью этой директивы. Это одна из тех директив, которые я использую в каждом из моих проектов. Она очень удобна при работе с всплывающими или выпадающими меню.

    Hide me when a click outside this element happens

export default {
  data() {
    return {
      show: true

  methods: {
    onClickOutside() { = false;

Примечание. По умолчанию метод запускается при двойном клике снаружи. Обратитесь к документации, чтобы узнать больше об этой директиве.

Getting Started

The official guide assumes intermediate level knowledge of HTML, CSS, and JavaScript. 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 file and include Vue with:


The Installation page provides more options of installing Vue. Note: We do not recommend that beginners start with , 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.

Non-Prop Attributes

A non-prop attribute is an attribute that is passed to a component, but does not have a corresponding prop defined.

While explicitly defined props are preferred for passing information to a child component, authors of component libraries can’t always foresee the contexts in which their components might be used. That’s why components can accept arbitrary attributes, which are added to the component’s root element.

For example, imagine we’re using a 3rd-party component with a Bootstrap plugin that requires a attribute on the . We can add this attribute to our component instance:

And the attribute will automatically be added to the root element of .

Replacing/Merging with Existing Attributes

Imagine this is the template for :

To specify a theme for our date picker plugin, we might need to add a specific class, like this:

In this case, two different values for are defined:

  • , which is set by the component in its template
  • , which is passed to the component by its parent

For most attributes, the value provided to the component will replace the value set by the component. So for example, passing will replace and probably break it! Fortunately, the and attributes are a little smarter, so both values are merged, making the final value: .

Disabling Attribute Inheritance

If you do not want the root element of a component to inherit attributes, you can set in the component’s options. For example:

This can be especially useful in combination with the instance property, which contains the attribute names and values passed to a component, such as:

With and , you can manually decide which element you want to forward attributes to, which is often desirable for :

Note that option does not affect and bindings.

This pattern allows you to use base components more like raw HTML elements, without having to care about which element is actually at its root:

##company## — ##description##

Edit this on GitHub! Netlify


The built-in v-for directive allows us to loop through items in an array or object.

We can loop over items in our array from the data model. This can be done by adding the v-for directive in the element that should be repeated.

This will output an unordered list with the values from the array.

Similarly, we can loop over the objects in the array. Here we can access the values using a given key (ex-

<template> element

The v-for directive only applies to the element that it’s attached to. If multiple items should repeat with the v-for directive, we should wrap the elements in a <template> element.

V-for with Objects

We can loop over objects with multiple properties like we do with arrays:

In the above example, we’re printing out the items (‘item1’, ‘item2’, ‘item3’).

In addition to the property value, we get two additional parameters when looping over objects with Vue. Namely, the key and the index values.

The key value gives us access to the current properties key (‘key1’, ‘key2’, ‘key3’).

The index provides us the index of the current item in the loop. This is simply the position of the item in the looped list (0, 1, 2).

V-for with Range

We can use a range in the v-for directive to iterate a specified number of times.

The following syntax would print out 1 to 15 in an unordered list:

Отслеживание изменений в массивах

Методы внесения изменений

Vue оборачивает у наблюдаемого массива методы внесения изменений, чтобы они вызывали обновления представления. Оборачиваются следующие методы:

Можете открыть консоль и поиграть с массивом из предыдущего примера, вызывая его методы внесения изменений, например: .

Замены в массиве

Методы внесения изменений, как следует из их названия, изменяют оригинальный массив, на котором они вызываются. Существуют и неизменяющие методы, такие как , и , они не вносят изменений в изначальный массив, а всегда возвращают новый массив. При работе с неизменяющими методами можно просто заменять старый массив на новый:

Можно предположить, что Vue придётся выбросить существующий DOM и заново отрисовать список целиком, но, к счастью, это не так. Во Vue есть умные эвристики для максимизации переиспользования элементов DOM, поэтому замена одного массива другим, в случае совпадения части элементов этих массивов, будет очень эффективной операцией.


Вследствие ограничений JavaScript, есть виды изменений, которые Vue не может обнаружить при работе с массивами и объектами. Это обсуждается в разделе .

Listening to Child Components Events

As we develop our component, some features may require communicating back up to the parent. For example, we may decide to include an accessibility feature to enlarge the text of blog posts, while leaving the rest of the page its default size:

In the parent, we can support this feature by adding a data property:

Which can be used in the template to control the font size of all blog posts:

Now let’s add a button to enlarge the text right before the content of every post:

The problem is, this button doesn’t do anything:

When we click on the button, we need to communicate to the parent that it should enlarge the text of all posts. Fortunately, Vue instances provide a custom events system to solve this problem. The parent can choose to listen to any event on the child component instance with , just as we would with a native DOM event:

Then the child component can emit an event on itself by calling the built-in , passing the name of the event:

Thanks to the listener, the parent will receive the event and update value.

Filtering list

We can filter out lists that are being displayed without changing the original list. This can be done using computed values or simply by having a method and passing values through when setting the v-for values.

Using computed values to filter items

Instead of setting the value directly on the list, we instead point to a computed value. We can write the logic for filtering out data in that computed function.

The function simply uses the JS filter function to return any item who’s price is less than 10.

Using a method to filter items

In this approach, we pass in the same list directly to a method that we define. By doing so, all the items in the array would be filtered according to the method definition.

Here, we are passing the list though the method.



Наиболее простой способ связывания данных — это текстовая интерполяция с использованием синтаксиса Mustache (двойных фигурных скобок):

Выражение в фигурных скобках будет заменено значением свойства соответствующего объекта данных. Кроме того, оно будет обновлено при любом изменении этого свойства.

Возможно также выполнение интерполяции однократно, которая не обновится при изменении данных — с помощью , но обратите внимание, это повлияет сразу на все связанные переменные в рамках данного элемента:

Сырой HTML

Значение выражения в двойных фигурных скобках подставляется как простой текст, а не как HTML. Для HTML необходимо использовать :

Двойные фигурные скобки: {{ rawHtml }}

Директива v-html:

Содержимое тега будет заменено значением свойства , интерпретированного как обычный HTML — все привязки данных игнорируются. Запомните, вы не можете использовать для вложения шаблонов друг в друга, потому что движок шаблонов Vue не основывается на строках. Вместо этого нужно использовать компоненты, позволяющие сочетать и переиспользовать элементы UI.

Динамическая отрисовка произвольного HTML-кода на вашем сайте крайне опасна, так как может легко привести к XSS-уязвимостям. Используйте интерполяцию HTML только для доверенного кода, и никогда не подставляйте туда содержимое, создаваемое пользователями.


Синтаксис двойных фигурных скобок не работает с HTML-атрибутами. Используйте вместо него :

При использовании с булевыми атрибутами (когда их наличие уже означает ) работает немного иначе. В этом примере:

Если значением будет , или , то атрибут не добавится в элемент .

Использование выражений JavaScript

Пока мы связывали данные со свойствами в шаблонах только по простым ключам. Но на самом деле при связывании данных Vue поддерживает всю мощь выражений JavaScript:

Выражения будут вычислены как JavaScript-код в области видимости соответствующего экземпляра Vue. Единственное ограничение в том, что допускается лишь одно выражение, поэтому код ниже НЕ сработает:

Выражения в шаблонах выполняются в режиме «песочницы», поэтому доступ есть только к глобальных объектов, таким как и . Не пытайтесь получить доступ к пользовательским глобальным объектам внутри выражений используемых в шаблонах.

Общие сведения

Vue даёт возможность самым разным образом анимировать переходы при обновлении объектов DOM, а также при их добавлении и удалении. Его инструменты дают возможность:

  • автоматически применять CSS-классы для анимаций и переходов
  • интегрировать сторонние библиотеки CSS-анимаций, такие как Animate.css
  • использовать JavaScript для работы с DOM напрямую в хуках переходов
  • интегрировать сторонние библиотеки JavaScript-анимаций, такие как Velocity.js

На этой странице мы рассмотрим только анимации появления и исчезновения элементов, а также анимации списков. В следующем разделе вы можете найти информацию об анимировании переходов между состояниями.

Dynamic Transitions

Yes, even transitions in Vue are data-driven! The most basic example of a dynamic transition binds the attribute to a dynamic property.

This can be useful when you’ve defined CSS transitions/animations using Vue’s transition class conventions and want to switch between them.

Really though, any transition attribute can be dynamically bound. And it’s not only attributes. Since event hooks are methods, they have access to any data in the context. That means depending on the state of your component, your JavaScript transitions can behave differently.

Fade In: Fade Out:


Start animating Stop it!

Finally, the ultimate way of creating dynamic transitions is through components that accept props to change the nature of the transition(s) to be used. It may sound cheesy, but the only limit really is your imagination.

##company## — ##description##

Edit this on GitHub! Netlify

Organizing Components

It’s common for an app to be organized into a tree of nested components:

For example, you might have components for a header, sidebar, and content area, each typically containing other components for navigation links, blog posts, etc.

To use these components in templates, they must be registered so that Vue knows about them. There are two types of component registration: global and local. So far, we’ve only registered components globally, using :

Globally registered components can be used in the template of any root Vue instance () created afterwards – and even inside all subcomponents of that Vue instance’s component tree.

That’s all you need to know about registration for now, but once you’ve finished reading this page and feel comfortable with its content, we recommend coming back later to read the full guide on Component Registration.

Key Modifiers

When listening for keyboard events, we often need to check for specific keys. Vue allows adding key modifiers for when listening for key events:

You can directly use any valid key names exposed via as modifiers by converting them to kebab-case.

In the above example, the handler will only be called if is equal to .

Key Codes

The use of events is deprecated and may not be supported in new browsers.

Using attributes is also permitted:

Vue provides aliases for the most commonly used key codes when necessary for legacy browser support:

  • (captures both “Delete” and “Backspace” keys)

A few keys ( and all arrow keys) have inconsistent values in IE9, so these built-in aliases should be preferred if you need to support IE9.

You can also via the global object:

Module Systems

If you’re not using a module system with /, you can probably skip this section for now. If you are, we have some special instructions and tips just for you.

Local Registration in a Module System

If you’re still here, then it’s likely you’re using a module system, such as with Babel and Webpack. In these cases, we recommend creating a directory, with each component in its own file.

Then you’ll need to import each component you’d like to use, before you locally register it. For example, in a hypothetical or file:

Now both and can be used inside ‘s template.

Automatic Global Registration of Base Components

Many of your components will be relatively generic, possibly only wrapping an element like an input or a button. We sometimes refer to these as and they tend to be used very frequently across your components.

The result is that many components may include long lists of base components:

Just to support relatively little markup in a template:

Fortunately, if you’re using Webpack (or Vue CLI 3+, which uses Webpack internally), you can use to globally register only these very common base components. Here’s an example of the code you might use to globally import base components in your app’s entry file (e.g. ):

Remember that global registration must take place before the root Vue instance is created (with ). Here’s an example of this pattern in a real project context.

##company## — ##description##

Edit this on GitHub! Netlify

Dùng v-for với một object

Bạn cũng có thể dùng để duyệt qua các thuộc tính của một object.

<ul id="v-for-object" class="demo">  <li v-for="value in object">    {{ value }}  </li></ul>
new Vue({  el: '#v-for-object',  data: {    object: {      'họ': 'Bành',      'tên': 'Tổ',      'tuổi': 800    }  }})


{{ value }}

Bạn cũng có thể cung cấp tham số thứ hai dùng cho khóa (key) của thuộc tính:

<div v-for="(value, key) in object">  {{ key }}: {{ value }}</div>

{{ key }}: {{ value }}

Tham số thứ ba chỉ thứ tự của thuộc tính:

<div v-for="(value, key, index) in object">  {{ index }}. {{ key }}: {{ value }}</div>

{{ index }}. {{ key }}: {{ value }}

Khi duyệt qua một object, thứ tự các thuộc tính được dựa trên kết quả trả về của . Kết quả này không đảm bảo được đồng nhất giữa các engine JavaScript khác nhau.

Object v-for

You can also use to iterate through the properties of an Object. In addition to , each scope will have access to another special property .

<ul id="repeat-object" class="demo">  <li v-for="value in object">
    {{ $key }} : {{ value }}  </li>
new Vue({  el: '#repeat-object',  data: {    object: {      FirstName: 'John',      LastName: 'Doe',      Age: 30
    }  }})


{{ $key }} : {{ value }}

You can also provide an alias for the key:

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

When iterating over an Object, the order is based on the key enumeration order of , which is not guaranteed to be consistent in all JavaScript engine implementations.


In the year 1998 , Evey Hammond is an average citizen of the United Kingdom, which is under the rule of the fascist and tyrannical Norsefire Party. She is an employee of the state-run British Television Network, but soon, she becomes the number one enemy of the state together with an enigmatic and larger-than-life freedom fighter known only by the letter «V». V informs Evey that she must hide in his underground lair for at least one year, and while she is reluctant to the idea at first, a bond soon forms between the two individuals. In the meanwhile, the mysterious past of V is gradually revealed to the police inspector tasked with capturing him, Eric Finch, and it is not long until he starts questioning everything his government stands for. Written by goddangwatir

Plot Summary | Plot Synopsis


Remember, remember the 5th of November, the gun powder treason and plot. I know of no reason why the gun powder treason should ever be forgot. See more »

Array Change Detection

Mutation Methods

Vue.js wraps an observed Array’s mutation methods so they will also trigger View updates. The wrapped methods are:

You can open the console and play with the previous examples’ array by calling its mutation methods. For example: .

Replacing an Array

Mutation methods, as the name suggests, mutate the original Array they are called on. In comparison, there are also non-mutating methods, e.g. , and , which do not mutate the original Array but always return a new Array. When working with non-mutating methods, you can just replace the old Array with the new one:

example1.items = example1.items.filter(function (item) {  return item.message.match(/Foo/)})

You might think this will cause Vue.js to throw away the existing DOM and re-render the entire list — luckily that is not the case. Vue.js implements some smart heuristics to maximize DOM element reuse, so replacing an array with another array containing overlapping objects is a very efficient operation.


In some cases, you might need to replace the Array with completely new objects — e.g. ones created from an API call. Since by default determines the reusability of existing scopes and DOM elements by tracking the identity of its data object, this could cause the entire list to be re-rendered. However, if each of your data objects has a unique id property, then you can use a special attribute to give Vue.js a hint so that it can reuse existing instances as much as possible.

For example, if your data looks like this:

{  items: [    { _uid: '88f869d', ... },    { _uid: '7496c10', ... }}

Then you can give the hint like this:

<div v-for="item in items" track-by="_uid">  

Later on, when you replace the array and Vue.js encounters a new object with , it knows it can reuse the existing scope and DOM elements associated with the same .

track-by $index

If you don’t have a unique key to track by, you can also use , which will force into in-place update mode: fragments are no longer moved around, they simply get flushed with the new value at the corresponding index. This mode can also handle duplicate values in the source array.

This can make Array replacement extremely efficient, but it comes at a trade-off. Because DOM nodes are no longer moved to reflect the change in order, temporary state like DOM input values and component private state can become out of sync. So, be careful when using if the block contains form input elements or child components.


Due to limitations of JavaScript, Vue.js cannot detect the following changes to an Array:

  1. When you directly set an item with the index, e.g. ;
  2. When you modify the length of the Array, e.g. .

To deal with caveat (1), Vue.js augments observed Arrays with a method:

example1.items.$set(, { childMsg: 'Changed!'})

To deal with caveat (2), just replace with an empty array instead.

In addition to , Vue.js also augments Arrays with a convenience method , which searches for and removes an item from target Array by calling internally. So instead of:

var index = this.items.indexOf(item)
if (index !== -1) {  this.items.splice(index, 1)}

You can just do:



When iterating over an array of objects frozen with , you need to explicitly use a key. A warning will be displayed in this scenario when Vue.js is unable to track objects automatically.


We can use the directive to render a list of items based on an Array. The directive requires a special syntax in the form of , where is the source data Array and is an alias for the Array element being iterated on:


<ul id="example-1">  <li v-for="item in items">
    {{ item.message }}  </li>
var example1 = new Vue({  el: '#example-1',  data: {    items: [      { message: 'Foo' },      { message: 'Bar' }  }})



Inside blocks we have full access to parent scope properties, plus a special variable which, as you probably have guessed, is the Array index for the current item:

<ul id="example-2">  <li v-for="item in items">
    {{ parentMessage }} - {{ $index }} - {{ item.message }}  </li>
var example2 = new Vue({  el: '#example-2',  data: {    parentMessage: 'Parent',    items: [      { message: 'Foo' },      { message: 'Bar' }  }})


{{ parentMessage }} — {{ $index }} — {{ item.message }}

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

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

Starting in 1.0.17 you can also use as the delimiter instead of , so that it is closer to JavaScript syntax for iterators:

<div v-for="item of items"></div>

С этим читают