Local Registration

Global registration often isn’t ideal. For example, if you’re using a build system like Webpack, globally registering all components means that even if you stop using a component, it could still be included in your final build. This unnecessarily increases the amount of JavaScript your users have to download.

In these cases, you can define your components as plain JavaScript objects:

Then define the components you’d like to use in a option:

For each property in the object, the key will be the name of the custom element, while the value will contain the options object for the component.

Note that locally registered components are not also available in subcomponents. For example, if you wanted to be available in , you’d have to use:

Or if you’re using ES2015 modules, such as through Babel and Webpack, that might look more like:

Note that in ES2015+, placing a variable name like inside an object is shorthand for , meaning the name of the variable is both:

  • the custom element name to use in the template, and
  • the name of the variable containing the component options

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.



The most basic form of data binding is text interpolation using the “Mustache” syntax (double curly braces):

The mustache tag will be replaced with the value of the property on the corresponding data object. It will also be updated whenever the data object’s property changes.

You can also perform one-time interpolations that do not update on data change by using the , but keep in mind this will also affect any other bindings on the same node:


The double mustaches interprets the data as plain text, not HTML. In order to output real HTML, you will need to use the :

Using mustaches: {{ rawHtml }}

Using v-html directive:

The contents of the will be replaced with the value of the property, interpreted as plain HTML — data bindings are ignored. Note that you cannot use to compose template partials, because Vue is not a string-based templating engine. Instead, components are preferred as the fundamental unit for UI reuse and composition.

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


Mustaches cannot be used inside HTML attributes. Instead, use a :

In the case of boolean attributes, where their mere existence implies , works a little differently. In this example:

If has the value of , , or , the attribute will not even be included in the rendered element.

Using JavaScript Expressions

So far we’ve only been binding to simple property keys in our templates. But Vue.js actually supports the full power of JavaScript expressions inside all data bindings:

These expressions will be evaluated as JavaScript in the data scope of the owner Vue instance. One restriction is that each binding can only contain one single expression, so the following will NOT work:

Template expressions are sandboxed and only have access to a such as and . You should not attempt to access user-defined globals in template expressions.

A Single Root Element

When building out a component, your template will eventually contain more than just the title:

At the very least, you’ll want to include the post’s content:

If you try this in your template however, Vue will show an error, explaining that every component must have a single root element. You can fix this error by wrapping the template in a parent element, such as:

As our component grows, it’s likely we’ll not only need the title and content of a post, but also the published date, comments, and more. Defining a prop for each related piece of information could become very annoying:

So this might be a good time to refactor the component to accept a single prop instead:

The above example and some future ones use JavaScript’s template literal to make multi-line templates more readable. These are not supported by Internet Explorer (IE), so if you must support IE and are not transpiling (e.g. with Babel or TypeScript), use newline escapes instead.

Now, whenever a new property is added to objects, it will automatically be available inside .



Концепция V-образной модели была разработана Германией и США в конце 1980-х годов независимо друг от друга:

  • Немецкая V-модель была разработана аэрокосмической компанией IABG в Оттобрунне рядом с Мюнхеном в содействии с Федеральным департаментом по закупке вооружений в Кобленце, для Министерства обороны Германии. Модель была принята немецкой федеральной администрацией для гражданских нужд летом 1992.
  • Американская V-Model (VEE) была разработана национальным советом по системной инженерии (международным — с 1995 года) для спутниковых систем, включая оборудование, программное обеспечение и взаимодействие с пользователями.

Современной версией V-Model является V-Model XT, которая была утверждена в феврале 2005 года. V-модель используется для управления процессом разработки программного обеспечения для немецкой федеральной администрации. Сейчас она является стандартом для немецких правительственных и оборонных проектов, а также для производителей ПО в Германии. V-Model представляет собой скорее набор стандартов в области проектов, касающихся разработки новых продуктов. Эта модель во многом схожа с PRINCE2 и описывает методы как для проектного управления, так и для системного развития.

Основные принципы

V-Model процесса разработки ИС.

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

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


V-модель обеспечивает поддержку в планировании и реализации проекта. В ходе проекта ставятся следующие задачи:

  • Минимизация рисков: V-образная модель делает проект более прозрачным и повышает качество контроля проекта путём стандартизации промежуточных целей и описания соответствующих им результатов и ответственных лиц. Это позволяет выявлять отклонения в проекте и риски на ранних стадиях и улучшает качество управления проектов, уменьшая риски.
  • Повышение и гарантии качества: V-Model — стандартизованная модель разработки, что позволяет добиться от проекта результатов желаемого качества. Промежуточные результаты могут быть проверены на ранних стадиях. Универсальное документирование облегчает читаемость, понятность и проверяемость.
  • Уменьшение общей стоимости проекта: Ресурсы на разработку, производство, управление и поддержку могут быть заранее просчитаны и проконтролированы. Получаемые результаты также универсальны и легко прогнозируются. Это уменьшает затраты на последующие стадии и проекты.
  • Повышение качества коммуникации между участниками проекта: Универсальное описание всех элементов и условий облегчает взаимопонимание всех участников проекта. Таким образом, уменьшаются неточности в понимании между пользователем, покупателем, поставщиком и разработчиком.


  • Пользователи V-Model участвуют в разработке и поддержке V-модели. Комитет по контролю за изменениями поддерживает проект и собирается раз в год для обработки всех полученных запросов на внесение изменений в V-Model.
  • На старте любого проекта V-образная модель может быть адаптирована под этот проект, так как эта модель не зависит от типов организаций и проектов.
  • V-model позволяет разбить деятельность на отдельные шаги, каждый из которых будет включать в себя необходимые для него действия, инструкции к ним, рекомендации и подробное объяснение деятельности.


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

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

.sync Modifier

In some cases, we may need “two-way binding” for a prop. Unfortunately, true two-way binding can create maintenance issues, because child components can mutate the parent without the source of that mutation being obvious in both the parent and the child.

That’s why instead, we recommend emitting events in the pattern of . For example, in a hypothetical component with a prop, we could communicate the intent of assigning a new value with:

Then the parent can listen to that event and update a local data property, if it wants to. For example:

For convenience, we offer a shorthand for this pattern with the modifier:

Note that with the modifier does not work with expressions (e.g. is invalid). Instead, you must only provide the name of the property you want to bind, similar to .

The modifier can also be used with when using an object to set multiple props at once:

This passes each property in the object (e.g. ) as an individual prop, then adds update listeners for each one.

Using with a literal object, such as in , will not work, because there are too many edge cases to consider in parsing a complex expression like this.

##company## — ##description##

Edit this on GitHub! Netlify



  • В модели особое значение придается планированию, направленному на верификацию и аттестацию разрабатываемого продукта на ранних стадиях его разработки. Фаза модульного тестирования подтверждает правильность детализированного проектирования. Фазы интеграции и тестирования реализуют архитектурное проектирование или проектирование на высшем уровне. Фаза тестирования системы подтверждает правильность выполнения этапа требований к продукту и его спецификации.
  • В модели предусмотрены аттестация и верификация всех внешних и внутренних полученных данных, а не только самого программного продукта.
  • В V-образной модели определение требований выполняется перед разработкой проекта системы, а проектирование ПО — перед разработкой компонентов.
  • Модель определяет продукты, которые должны быть получены в результате процесса разработки, причём каждые полученные данные должны подвергаться тестированию.
  • Благодаря модели менеджеры проекта могут отслеживать ход процесса разработки, так как в данном случае вполне возможно воспользоваться временной шкалой, а завершение каждой фазы является контрольной точкой.


  • Модель не предусматривает работу с параллельными событиями.
  • В модели не предусмотрено внесение требования динамических изменений на разных этапах жизненного цикла.
  • Тестирование требований в жизненном цикле происходит слишком поздно, вследствие чего невозможно внести изменения, не повлияв при этом на график выполнения проекта.
  • В модель не входят действия, направленные на анализ рисков.
  • Некоторый результат можно посмотреть только при достижении низа буквы V.

Controlling Updates

Thanks to Vue’s Reactivity system, it always knows when to update (if you use it correctly). There are edge cases, however, when you might want to force an update, despite the fact that no reactive data has changed. Then there are other cases when you might want to prevent unnecessary updates.

Forcing an Update

If you find yourself needing to force an update in Vue, in 99.99% of cases, you’ve made a mistake somewhere.

You may not have accounted for change detection caveats or , or you may be relying on state that isn’t tracked by Vue’s reactivity system, e.g. with .

However, if you’ve ruled out the above and find yourself in this extremely rare situation of having to manually force an update, you can do so with .

Cheap Static Components with

Rendering plain HTML elements is very fast in Vue, but sometimes you might have a component that contains a lot of static content. In these cases, you can ensure that it’s only evaluated once and then cached by adding the directive to the root element, like this:

Once again, try not to overuse this pattern. While convenient in those rare cases when you have to render a lot of static content, it’s simply not necessary unless you actually notice slow rendering – plus, it could cause a lot of confusion later. For example, imagine another developer who’s not familiar with or simply misses it in the template. They might spend hours trying to figure out why the template isn’t updating correctly.

##company## — ##description##

Edit this on GitHub! Netlify

Alternate Template Definitions

Inline Templates

When the special attribute is present on a child component, the component will use its inner content as its template, rather than treating it as distributed content. This allows more flexible template-authoring.

Your inline template needs to be defined inside the DOM element to which Vue is attached.

However, makes the scope of your templates harder to reason about. As a best practice, prefer defining templates inside the component using the option or in a element in a file.


Another way to define templates is inside of a script element with the type , then referencing the template by an id. For example:

Your x-template needs to be defined outside the DOM element to which Vue is attached.

These can be useful for demos with large templates or in extremely small applications, but should otherwise be avoided, because they separate templates from the rest of the component definition.

Key Software Engineering Terms:

SDLC: SDLC is Software Development Life Cycle. It is the sequence of activities carried out by Developers to design and develop high-quality software.

STLC: STLC is Software Testing Life Cycle. It consists of a series of activities carried out by Testers methodologically to test your software product.

Waterfall Model: Waterfall model is a sequential model divided into different phases of software development activity. Each stage is designed for performing the specific activity. Testing phase in waterfall model starts only after implementation of the system is done.


The prefix serves as a visual cue for identifying Vue-specific attributes in your templates. This is useful when you are using Vue.js to apply dynamic behavior to some existing markup, but can feel verbose for some frequently used directives. At the same time, the need for the prefix becomes less important when you are building a SPA, where Vue manages every template. Therefore, Vue provides special shorthands for two of the most often used directives, and :



They may look a bit different from normal HTML, but and are valid characters for attribute names and all Vue-supported browsers can parse it correctly. In addition, they do not appear in the final rendered markup. The shorthand syntax is totally optional, but you will likely appreciate it when you learn more about its usage later.

##company## — ##description##

Edit this on GitHub! Netlify

Array Change Detection

Mutation Methods

Vue 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 their 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 replace the old array with the new one:

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


Due to limitations in JavaScript, there are types of changes that Vue cannot detect with arrays and objects. These are discussed in the section.

V- Model ─ Application

V- Model application is almost the same as the waterfall model, as both the models are of sequential type. Requirements have to be very clear before the project starts, because it is usually expensive to go back and make changes. This model is used in the medical development field, as it is strictly a disciplined domain.

The following pointers are some of the most suitable scenarios to use the V-Model application.

  • Requirements are well defined, clearly documented and fixed.

  • Product definition is stable.

  • Technology is not dynamic and is well understood by the project team.

  • There are no ambiguous or undefined requirements.

  • The project is short.

Data and Methods

When a Vue instance is created, it adds all the properties found in its 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 are only reactive if they existed when the instance was created. That means if you add a new property, like:

Then changes to 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. For example:

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

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. For example:

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

Cách sử dụng cơ bản

Bạn có thể sử dụng directive để tạo ràng buộc dữ liệu 2 chiều lên các phần tử form input và textarea. Vue sẽ tự động chọn cách phù hợp để cập nhật phần tử này dựa trên kiểu của input. Có một chút ma thuật, là syntax sugar trong việc cập nhật dữ liệu dựa trên các sự kiện input từ người dùng kèm theo một số trường hợp đặc biệt khác.

sẽ bỏ qua giá trị khởi tạo của các thuộc tính , hoặc trong mọi phần tử form. Nó luôn luôn xem data trong đối tượng Vue là nguồn đáng tin cậy duy nhất. Bạn nên khai báo các giá trị khởi tạo trong JavaScript, bên trong option của component.

Đối với các ngôn ngữ đòi hỏi bộ gõ (IME) (tiếng Trung, tiếng Nhật, Tiếng Hàn v.v.), bạn sẽ nhận thấy rằng không thay đổi trong quá trình biên soạn của IME. Nếu bạn muốn nhận các thay đổi này thì phải sử dụng sự kiện .

Văn bản

<input v-model="message" placeholder="Nhập thông điệp"><p>Thông điệp: {{ message }}</p>

Thông điệp: {{ message }}

Văn bản nhiều dòng

<span>Thông điệp có nhiều dòng:</span><p style="white-space: pre-line;">{{ message }}</p><br><textarea v-model="message" placeholder="Nhập văn bản có nhiều dòng"></textarea>

Thông điệp có nhiều dòng:

{{ message }}

Nội suy () không hoạt động với textarea. Hãy sử dụng .


Checkbox đơn, giá trị boolean:

<input type="checkbox" id="checkbox" v-model="checked"><label for="checkbox">{{ checked }}</label>

{{ checked }}

Nhiều checkbox, ràng buộc vào cùng một mảng:

<div id='example-3'>  <input type="checkbox" id="com-chien-toi" value="Cơm chiên tỏi" v-model="checkedNames">  <label for="com-chien-toi">Cơm chiên tỏi</label><br>  <input type="checkbox" id="dot-bi-xao-toi" value="Đọt bí xào tỏi" v-model="checkedNames">  <label for="dot-bi-xao-toi">Đọt bí xào tỏi</label><br>  <input type="checkbox" id="canh-rau-rung" value="Canh rau rừng" v-model="checkedNames">  <label for="canh-rau-rung">Canh rau rừng</label>  <br>  <span>Món đã chọn: {{ checkedNames }}</span></div>
new Vue({  el: '#example-3',  data: {    checkedNames: []  }})

Cơm chiên tỏiĐọt bí xào tỏiCanh rau rừng Món đã chọn: {{ checkedNames }}


<input type="radio" id="cac-mon-rau" value="Các món rau" v-model="picked"><label for="cac-mon-rau">Các món rau</label><br><input type="radio" id="cac-mon-thit" value="Các món thịt" v-model="picked"><label for="cac-mon-thit">Các món thịt</label><br><span>Đã chọn: {{ picked }}</span>

Các món rauCác món thịtĐã chọn: {{ picked }}


Select đơn:

<select v-model="selected">  <option disabled value="">Vui lòng chọn món</option>  <option>Đọt bí xào tỏi</option>  <option>Canh bông điên điển</option>  <option>Lẩu nấm</option></select><span>Món đã chọn: {{ selected }}</span>
new Vue({  el: '...',  data: {    selected: ''  }})

Vui lòng chọn mónĐọt bí xào tỏiCanh bông điên điểnLẩu nấmMón đã chọn: {{ selected }}

Nếu giá trị khởi tạo của biểu thức trong không khớp với bất kỳ option nào, thì sẽ render ở trạng thái “chưa được chọn”. Trên iOS nó sẽ làm cho người dùng không thể chọn item đầu tiên bởi vì iOS không gọi sự kiện change trong trường hợp này. Do đó chúng tôi khuyên bạn nên thêm một lựa chọn có giá trị rỗng giống như trong ví dụ trên.

Select nhiều lựa chọn (được ràng buộc với một mảng):

<select v-model="selected" multiple>   <option>Đọt bí xào tỏi</option>   <option>Canh bông điên điển</option>   <option>Lẩu nấm</option></select><br><span>Món đã chọn: {{ selected }}</span>

Đọt bí xào tỏiCanh bông điên điểnLẩu nấmMón đã chọn: {{ selected }}

Render với :

<select v-model="selected">  <option v-for="option in options" v-bind:value="option.value">    {{ option.text }}  </option></select><span>Giá tiền: {{ selected }}</span>
new Vue({  el: '...',  data: {    selected: '50k',    options: [      { text: 'Đọt bí xào tỏi', value: '50k' },      { text: 'Canh bông điên điển', value: '30k' },      { text: 'Lẩu nấm', value: '45k' }  }})

{{ option.text }} Giá tiền: {{ selected }}

Prop Validation

Components can specify requirements for their props, such as the types you’ve already seen. If a requirement isn’t met, Vue will warn you in the browser’s JavaScript console. This is especially useful when developing a component that’s intended to be used by others.

To specify prop validations, you can provide an object with validation requirements to the value of , instead of an array of strings. For example:

When prop validation fails, Vue will produce a console warning (if using the development build).

Note that props are validated before a component instance is created, so instance properties (e.g. , , etc) will not be available inside or functions.

Type Checks

The can be one of the following native constructors:

  • String
  • Number
  • Boolean
  • Array
  • Object
  • Date
  • Function
  • Symbol

In addition, can also be a custom constructor function and the assertion will be made with an check. For example, given the following constructor function exists:

You could use:

to validate that the value of the prop was created with .


The directive is used to conditionally render a block. The block will only be rendered if the directive’s expression returns a truthy value.

It is also possible to add an “else block” with :

Conditional Groups with on

Because is a directive, it has to be attached to a single element. But what if we want to toggle more than one element? In this case we can use on a element, which serves as an invisible wrapper. The final rendered result will not include the element.

You can use the directive to indicate an “else block” for :

A element must immediately follow a or a element — otherwise it will not be recognized.

The , as the name suggests, serves as an “else if block” for . It can also be chained multiple times:

Similar to , a element must immediately follow a or a element.

Controlling Reusable Elements with

Vue tries to render elements as efficiently as possible, often re-using them instead of rendering from scratch. Beyond helping make Vue very fast, this can have some useful advantages. For example, if you allow users to toggle between multiple login types:

Then switching the in the code above will not erase what the user has already entered. Since both templates use the same elements, the is not replaced — just its .

Check it out for yourself by entering some text in the input, then pressing the toggle button:

This isn’t always desirable though, so Vue offers a way for you to say, “These two elements are completely separate — don’t re-use them.” Add a attribute with unique values:

Now those inputs will be rendered from scratch each time you toggle. See for yourself:

Note that the elements are still efficiently re-used, because they don’t have attributes.

Flat Mode & Sort Values

In all previous examples, we used the default non-flat mode of vue-treeselect, which means:

  1. Whenever a branch node gets checked, all its children will be checked too
  2. Whenever a branch node has all children checked, the branch node itself will be checked too

Sometimes we don’t need that mechanism, and want branch nodes & leaf nodes don’t affect each other. In this case, flat mode should be used, as demonstrated in the following.

If you want to control the order in which selected options to be displayed, use the prop. This prop has three options:

  • (default) — Order selected
  • — Level of option: C 🡒 BB 🡒 AAA
  • — Index of option: AAA 🡒 BB 🡒 C

С этим читают