Article directory
-
- Introduction to v-html
-
- What is v-html?
- Basic usage
- security considerations
- Introduction to v-show and v-if
-
- v-show
- v-if
- Differences and choices
- Sample code
- Introduction to v-on command
-
- Basic usage
- Short form of v-on
- Introduction to v-bind command
-
- Dynamically binding class and style
-
- dynamic binding class
- Dynamic binding style
- Short form of v-bind
- Introduction to v-for
-
- What is v-for?
- Basic usage
- Traverse objects
- Traverse index
- Importance of key attribute
- event modifier
- v-model modifier
- Key modifier
-
- Common key modifiers
- Custom key modifiers
v-html Introduction
What is v-html?
In Vue.js, v-html
is a directive used to render a piece of HTML code into an element. Normally, Vue will display the text entered by the user as plain text, but in some cases, it may be necessary to render HTML tags, in which case v-html
can be used.
Basic usage
To use v-html
in Vue, first ensure that the data contains HTML code, and then bind the data to the element that needs to render HTML.
<template> <div> <p v-html="htmlContent"></p> </div> </template> <script> export default {<!-- --> data() {<!-- --> return {<!-- --> htmlContent: '<strong>This is bold text</strong>' }; } } </script>
In the above example, the v-html
directive renders the value of htmlContent
into HTML and displays it in
element. Will appear as bold text on the page.
Security considerations
Be extra careful about security issues when using v-html
. If you get HTML code from an untrusted source and render it into your application, it can lead to a cross-site scripting attack (XSS). To ensure security, HTML coming from users or untrusted sources should always be trusted and verified.
Vue provides a tool function this.$sanitize
that can be used to filter unsafe HTML tags. This can be used to ensure that only safe markup is rendered before rendering the HTML.
<template> <div> <p v-html="sanitizeHTML(htmlContent)"></p> </div> </template> <script> export default {<!-- --> data() {<!-- --> return {<!-- --> htmlContent: '<script>alert("Malicious Script");</script>' }; }, methods: { sanitizeHTML(html) { // Use $sanitize to filter HTML return this.$sanitize(html); } } } </script>
This will ensure that only safe HTML markup is rendered onto the page, preventing potential security issues.
When using Vue.js, you will often encounter situations where you need to show or hide elements based on conditions. Vue provides two main instructions to achieve this purpose: v-show
and v-if
. In this blog, we’ll take a deeper look at the usage of these two directives, their differences, and when to use them.
Introduction to v-show and v-if
v-show
v-show
is a directive in Vue.js, used to control the display and hiding of elements based on conditions. The way it works is to control the visibility of an element by modifying its CSS property (display
).
<template> <div> <p v-show="isVisible">This is a visible paragraph.</p> </div> </template> <script> export default {<!-- --> data() {<!-- --> return {<!-- --> isVisible: true }; } } </script>
In the above example, when isVisible
is true
, the paragraph will be visible. If isVisible
is false
, the paragraph will be hidden, but it will still exist in the DOM.
v-if
v-if
is also a directive for conditionally rendering elements, but it works differently. It completely adds or removes elements from the DOM, rather than just modifying CSS properties.
<template> <div> <p v-if="isVisible">This is a visible paragraph.</p> </div> </template> <script> export default {<!-- --> data() {<!-- --> return {<!-- --> isVisible: true }; } } </script>
Unlike v-show
, when isVisible
is false
, elements using v-if
will be removed from the DOM Removed, and when isVisible
is true
, the element will be added back to the DOM.
Differences and choices
-
v-show
is more suitable for elements that need to frequently switch visibility, because it only switches CSS properties and does not cause the DOM to be re-rendered. This is useful in situations where performance requirements are high. -
v-if
is suitable for elements whose visibility is toggled infrequently, as it adds or removes elements from the DOM based on conditions. This can reduce unnecessary DOM nodes, but may cause performance issues when switching frequently. -
If you’re not sure which directive to use, consider using
v-if
first. If performance becomes an issue, then consider switching tov-show
. -
In addition, if you need to perform some complex calculations or asynchronous operations on the initial state of the element,
v-if
may be more suitable, since it will only work if the condition istrue
These operations will be performed.
Example code
The following example demonstrates the difference between v-show
and v-if
:
<template> <div> <button @click="toggleVisibility">Toggle visibility</button> <p v-show="isVisible">Use v-show to display the paragraph.</p> <p v-if="isVisible">Paragraph displayed using v-if.</p> </div> </template> <script> export default {<!-- --> data() {<!-- --> return {<!-- --> isVisible: true }; }, methods: {<!-- --> toggleVisibility() {<!-- --> this.isVisible = !this.isVisible; } } } </script>
Introduction to the v-on command
v-on
is a directive in Vue.js that is used to listen to DOM events and perform specified operations when the event is triggered. You can use it for various events such as clicks, mouse movements, keyboard input, etc.
Basic usage
Here is a basic example of using v-on
, which triggers a function when the button is clicked:
<template> <div> <button v-on:click="handleClick">Click me</button> </div> </template> <script> export default {<!-- --> methods: {<!-- --> handleClick() {<!-- --> //Perform click event operations here console.log("The button was clicked!"); } } } </script>
In the above example, v-on:click
listens for the click event of the button and calls the handleClick
method when triggered.
Short form of v-on
In order to simplify the code, Vue also provides the @
symbol as a shorthand form of v-on
. The above example can be rewritten as:
<template> <div> <button @click="handleClick">Click me</button> </div> </template> <script> export default {<!-- --> methods: {<!-- --> handleClick() {<!-- --> //Perform click event operations here console.log("The button was clicked!"); } } } </script>
The @
symbol has the same functionality as v-on
but is more concise.
In Vue.js, the v-bind
directive is a powerful tool for dynamically binding attributes of HTML elements. It allows you to set attribute values of elements based on data from the Vue instance, allowing you to update the page in a responsive manner. In addition, Vue also provides :
as the abbreviation of v-bind
, making the code more concise and readable. In this blog, we’ll take an in-depth look at the usage of v-bind
and its abbreviation.
Introduction to v-bind command
The v-bind
directive is used to bind the data of the Vue instance to the attributes of the HTML element. In this way, the element’s attribute values can be dynamically updated based on changes in data.
<template> <div> <a v-bind:href="url">Click to jump</a> </div> </template> <script> export default {<!-- --> data() {<!-- --> return {<!-- --> url: 'https://example.com' }; } } </script>
In the example above, v-bind:href
binds the url
data to the href
element of the element. >Attributes. When the
url
data changes, the link’s target is updated accordingly.
Dynamic binding class and style
In addition to binding properties, v-bind
can also be used to dynamically bind class
and style
. You can add different classes or styles to elements based on specific conditions.
Dynamic binding class
<template> <div> <div v-bind:class="{'active': isActive, 'error': hasError}">Dynamic binding class</div> </div> </template> <script> export default {<!-- --> data() {<!-- --> return {<!-- --> isActive: true, hasError: false }; } } </script>
In the above example, v-bind:class
dynamically adds active
and according to the values of
isActive
and hasError
error
class.
Dynamic binding style
<template> <div> <div v-bind:style="{ color: textColor, fontSize: fontSize + 'px' }">Dynamic binding style</div> </div> </template> <script> export default {<!-- --> data() {<!-- --> return {<!-- --> textColor: 'blue', fontSize: 16 }; } } </script>
v-bind:style
allows dynamically setting the CSS style of an element. In the example above, the values of textColor
and fontSize
will affect the text color and font size.
Short form of v-bind
To simplify the code, Vue provides :
as a shorthand form of v-bind
. The above example can be rewritten as:
<template> <div> <a :href="url">Click to jump</a> </div> </template> <script> export default {<!-- --> data() {<!-- --> return {<!-- --> url: 'https://example.com' }; } } </script>
Using :
as shorthand for v-bind
can make the code more compact and readable.
Introduction to v-for
What is v-for?
v-for
is a directive in Vue.js that is used to iterate over a collection of data, such as an array or object, in a template. With v-for
, you can create multiple repeating elements, each associated with an item in the data collection.
Basic usage
The following example demonstrates how to use v-for
to iterate over an array and render list items:
<template> <div> <ul> <li v-for="item in items">{<!-- -->{ item }}</li> </ul> </div> </template> <script> export default {<!-- --> data() {<!-- --> return {<!-- --> items: ['apple', 'banana', 'orange', 'grape'] }; } } </script>
In the above example, the v-for
directive is in
items
array and rendering it as a list item.
Traverse objects
v-for
can not only traverse arrays, but also traverse the properties of objects.
<template> <div> <ul> <li v-for="(value, key) in user">{<!-- -->{ key }}: {<!-- -->{ value }}</li> </ul> </div> </template> <script> export default {<!-- --> data() {<!-- --> return {<!-- --> user: {<!-- --> name: 'John', age: 30, occupation: 'Developer' } }; } } </script>
In this example, v-for
iterates over the properties of the user
object, rendering the keys and values respectively.
Traverse the index
Sometimes you may need to get the index of the current item, which can be achieved through the second parameter of v-for
:
<template> <div> <ul> <li v-for="(item, index) in items">{<!-- -->{ index + 1 }}. {<!-- -->{ item }}</li> </ul> </div> </template> <script> export default {<!-- --> data() {<!-- --> return {<!-- --> items: ['apple', 'banana', 'orange', 'grape'] }; } } </script>
In the above example, the index
parameter is used to get the index of the current item.
The importance of the key attribute
When using v-for
, be sure to set a unique key
attribute for each traversed element. This helps Vue manage updates to DOM elements more efficiently. If key
is not provided, Vue may experience performance issues or incorrect updates.
<template> <div> <ul> <li v-for="item in items" :key="item.id">{<!-- -->{ item.name }}</li> </ul> </div> </template> <script> export default {<!-- --> data() {<!-- --> return {<!-- --> items: [ {<!-- --> id: 1, name: 'Apple' }, {<!-- --> id: 2, name: 'Banana' }, {<!-- --> id: 3, name: 'Orange' }, {<!-- --> id: 4, name: 'Grape' } ] }; } } </script>
The example provides a unique key
attribute for each list item, which helps Vue accurately track and update DOM elements.
Event modifier
.stop
: Prevent event bubbling, that is, stop the event from propagating to the parent element.
<a v-on:click.stop="doThis"></a>
.prevent
: Prevent the default behavior of the event, such as preventing form submission.
<form v-on:submit.prevent="submitForm"> <!-- Form content --> </form>
.capture
: The event is triggered in capture mode instead of the default bubbling mode.
<div v-on:click.capture="handleClick"> <!-- Trigger in capture mode --> </div>
.self
: Only events on the event source element will be triggered, not on child elements.
<div v-on:click.self="handleClick"> <!-- Only triggered when this element is clicked, not triggered when clicking on child elements --> </div>
.once
: Ensure that the event is only triggered once, and then automatically unbind the event handler.
<button v-on:click.once="doThisOnce">Click once</button>
.passive
: used to improve the performance of scroll events. Event handlers do not cancel the event's default behavior.
<div v-on:scroll.passive="handleScroll"> <!-- Scroll event handling to improve performance --> </div>
v-model modifier
v-model
is a directive for two-way binding of form element values. Vue provides some modifiers to change the default behavior of v-model
.
.lazy
: By default,v-model
will synchronize the value of the input box when theinput
event is triggered. After using the.lazy
modifier, it will synchronize the value when thechange
event fires, instead of synchronizing every time it is entered.
<input v-model.lazy="message">
.number
: Normally,v-model
treats the input value as a string. After using the.number
modifier, it will convert the input value to a numeric type.
<input v-model.number="age" type="number">
.trim
: Normally,v-model
will preserve the leading and trailing whitespace of the input. After using the.trim
modifier, it will automatically remove leading and trailing whitespace.
<input v-model.trim="username">
Key modifier
Common key modifiers
.enter
: Used to monitor the press event of the Enter key (Enter).
<input v-on:keyup.enter="submitForm">
.tab
: Used to monitor the press event of the Tab key.
<input v-on:keydown.tab="focusNextInput">
.delete
: Used to monitor the press event of the delete key (Delete or Backspace).
<input v-on:keydown.delete="deleteItem">
.esc
: Used to monitor the Escape key press event.
<input v-on:keyup.esc="closeModal">
.space
: used to listen for the space key press event.
<button v-on:keydown.space="startVideoPlayback">Play video</button>
.up
: Used to monitor the press event of the up arrow key.
<input v-on:keydown.up="increaseValue">
.down
: Used to monitor the down arrow key press event.
<input v-on:keydown.down="decreaseValue">
Custom key modifier
In addition to the common key modifiers mentioned above, Vue.js also allows custom key modifiers to listen for specific keyboard keys. You can use Vue.config.keyCodes to register custom key modifiers.
//Register custom key modifiers Vue.config.keyCodes.myKey = 123; new Vue({<!-- --> el: '#app', methods: {<!-- --> customKeyHandler() {<!-- --> // Triggered when a custom button is pressed console.log('custom key pressed'); } } });
<!-- Use custom key modifiers in templates --> <input v-on:keydown.myKey="customKeyHandler">
The above example registers a custom key modifier named myKey
and maps it to the key with key code 123. This custom modifier is used in the template to listen for keyboard events.