Table of Contents
- 1 A Brief Overview of Vue.js and Its Benefits
- 2 Getting Started with Vue.js
- 2.1 Installing Vue.js
- 2.2 Setting up a Basic Vue.js Project
- 2.3 Understanding the Vue.js Instance, Components, and Directives
- 2.4 Overview of Vue.js elements and the virtual DOM
- 2.5 <component>
- 2.6 <slot>
- 2.7 <template>
- 2.8 Getting Elements Using the ref Attribute
- 2.9 Getting Elements Using the $refs Object
- 2.10 Common Use Cases and Best Practices for Getting Elements in Vue.js
- 3 Introduction to Element UI
- 4 Exploring Element UI Components
- 4.1 Overview of Element UI Components
- 4.2 Navigation Components (Menu, Tabs, Breadcrumb, etc.)
- 4.3 Menu
- 4.4 Navigation Components: Tabs
- 4.5 Basic Usage
- 4.6 Card Style
- 4.7 Border Card
- 4.8 Tab Position
- 4.9 Custom Tab
- 4.10 Add & Close Tab
- 4.11 Customized Trigger Button for New Tab
- 4.12 Navigation Components: Breadcrumb
- 4.13 Basic Usage
- 4.14 Icon Separator
- 4.15 Breadcrumb Attributes
- 4.16 Breadcrumb Item Attributes
- 4.17 Navigation Components: PageHeader
- 4.18 Basic Usage
- 4.19 Attributes
- 4.20 Events
- 4.21 Slots
- 4.22 Navigation Components: Dropdown
- 4.23 Basic Usage
- 4.24 Triggering Element
- 4.25 How to Trigger
- 4.26 Command Event
- 4.27 Sizes
- 5 Form components (Input, Radio, Checkbox, etc.)
- 6 Data components (Table, Tag, Tree, etc.)
- 7 Integrating Element UI with Vue.js
- 8 Customizing Element UI
- 9 Handling UI Events with Element UI and Vue.js
- 10 Best Practices and Tips for Using Element UI with Vue.js
- 11 Resources and Further Learning
- 12 Conclusion:
A Brief Overview of Vue.js and Its Benefits
Vue.js is a progressive JavaScript framework that’s designed to build user interfaces for web applications. It has gained immense popularity among developers due to its simplicity, flexibility, and performance. Vue.js allows you to create reusable UI components and manage the state of your application easily.
Some key benefits of Vue.js include:
- Easy learning curve: Vue.js is simple to understand, and its syntax is easy to grasp for developers, especially those familiar with HTML, CSS, and JavaScript.
- Reactivity: Vue.js has built-in reactivity, making it easy to manage changes in your application’s data and UI state.
- Component-based architecture: Vue.js encourages building applications with reusable components, promoting modularity and maintainability.
- Small bundle size: Vue.js has a small file size, which results in faster page load times and improved performance.
- Strong ecosystem: Vue.js has a robust ecosystem with numerous plugins, libraries, and UI toolkits available for developers to leverage in their projects.
Detailed article : Vue.js Templates: A Comprehensive Guide to Building Dynamic Web Applications
Introducing Element UI as a UI Toolkit for Vue.js
Element UI is a popular UI toolkit specifically designed for Vue.js. It provides a collection of ready-to-use components that can be easily integrated into your Vue.js project. Element UI streamlines the development process by offering a consistent and attractive design, as well as handling common functionalities like form validation, responsive layouts, and accessibility.
Element UI can be used in various scenarios, such as:
- Rapid prototyping
- Building admin panels or dashboards
- Creating responsive web applications
For example, you can use Element UI components like el-button
, el-input
, and el-table
to create a simple form and display the submitted data in a table.
The Importance of Getting Elements in Vue.js and Element UI
In Vue.js and Element UI, it’s sometimes necessary to get access to the DOM elements for tasks like focusing an input field, triggering animations, or integrating third-party libraries. Vue.js provides the ref
attribute to create a reference to a specific DOM element or Vue.js component instance.
Here’s an example of how you can use the ref
attribute to focus an input field in your Vue.js application:
<template> <div> <el-input ref="inputField" placeholder="Enter your name"></el-input> <el-button @click="focusInput">Focus input</el-button> </div> </template> <script> export default { methods: { focusInput() { this.$refs.inputField.focus(); }, }, }; </script>
In this example, the ref
attribute is used to create a reference to the el-input
component, and the focusInput
method focuses the input field when the button is clicked.
Objective of the Article and Target Audience
The main objective of this article is to provide a comprehensive understanding of Vue.js, Element UI, and the process of getting elements in your application. This article aims to cover key concepts, practical examples, and best practices for using Vue.js and Element UI effectively.
Our target audience includes:
- Beginners who are just starting with Vue.js and want to learn about its features and benefits
- Intermediate developers who are looking to enhance their Vue.js skills and learn about integrating Element UI in their projects
- Web developers who want to build modern and responsive web applications using Vue.js and Element UI
Getting Started with Vue.js
In this section, we’ll guide you through the process of installing Vue.js and setting up a basic Vue.js project. We’ll also help you understand the fundamental concepts of Vue.js, such as instances, components, and directives.
Installing Vue.js
Follow these step-by-step instructions to install Vue.js:
- Install Node.js: Vue.js requires Node.js to be installed on your system. Visit the official Node.js website and download the latest LTS version. Install it on your computer following the provided instructions.
- Install Vue.js CLI: Open your terminal or command prompt and enter the following command to install the Vue.js CLI globally:
npm install -g @vue/cli
The Vue.js CLI helps you create and manage Vue.js projects with ease.
Setting up a Basic Vue.js Project
With Vue.js CLI installed, you can now create a new Vue.js project by following these steps:
- Create a new project: In your terminal or command prompt, navigate to your preferred directory and run the following command to create a new Vue.js project:
vue create my-vue-project
Replace my-vue-project
with the desired name for your project.
- Select presets: The CLI will prompt you to choose presets for your project. For this tutorial, choose the default preset, which includes Babel and ESLint.
- Navigate to the project directory: Once the project is created, navigate to the project directory using the following command:
cd my-vue-project
- Start the development server: Run the following command to start the local development server:
npm run serve
Now, open your browser and visit http://localhost:8080/
. You should see the default Vue.js welcome page.
Understanding the Vue.js Instance, Components, and Directives
- Vue.js Instance: A Vue.js instance is an object that manages the state and behavior of a specific part of your application. It is created by calling
new Vue()
with an options object. The options object can include properties such asdata
,methods
,computed
, andwatch
.
Example of a Vue.js instance:
const app = new Vue({ el: '#app', data: { message: 'Hello, Vue.js!' } });
- Components: In Vue.js, components are reusable building blocks for your application’s UI. They help you create a modular and maintainable codebase. Components can have their own state, methods, and even other components.
Example of a Vue.js component:
Vue.component('hello-world', { template: '<p>{{ message }}</p>', data() { return { message: 'Hello, World!' }; } });
To use this component in your application, add the following line in your HTML:
<hello-world></hello-world>
- Directives: Directives are special HTML attributes that help you manipulate the DOM and bind data to your elements. They are prefixed with
v-
, such asv-if
,v-for
, andv-bind
.
Example of using directives:
<template> <div> <p v-if="showMessage">{{ message }}</p> <button v-on:click="toggleMessage">Toggle Message</button> </div> </template> <script> export default { data() { return { showMessage: true, message: 'Hello, Vue.js!' }; }, methods: { toggleMessage() { this.showMessage = !this.showMessage; }, }, }; </script>
In this example, the v-if
directive is used to conditionally display the message
paragraph based on the value of showMessage
. The v-on
directive binds the click
event of the button to the toggleMessage
method, which toggles the value of showMessage
.
Detailed article : Vue.js Template Components and Directives
Working with Elements in Vue.js
In this section, we will explore how to work with elements in Vue.js, including an overview of Vue.js elements and the virtual DOM, getting elements using the ref
attribute, and accessing elements with the $refs
object. We’ll also discuss common use cases and best practices for getting elements in Vue.js.
Overview of Vue.js elements and the virtual DOM
Vue.js provides several built-in special elements that help you create dynamic and flexible components. These elements are not true components, and they are compiled away during template compilation. As a result, they are conventionally written in lowercase in templates. In this section, we’ll discuss <component>
, <slot>
, and <template>
elements.
<component>
The <component>
element is a meta component used for rendering dynamic components or elements. The actual component to render is determined by the is
prop, which can be a string (HTML tag name or component’s registered name) or directly bound to a component definition.
Example:
- Rendering components by registered name (Options API):
<script> import Foo from './Foo.vue'; import Bar from './Bar.vue'; export default { components: { Foo, Bar }, data() { return { view: 'Foo', }; }, }; </script> <template> <component :is="view" /> </template>
- Rendering components by definition (Composition API with
<script setup>
):<script setup> import Foo from './Foo.vue'; import Bar from './Bar.vue'; </script> <template> <component :is="Math.random() > 0.5 ? Foo : Bar" /> </template>
- Rendering HTML elements:
<component :is="href ? 'a' : 'span'"></component>
<slot>
The <slot>
element denotes slot content outlets in templates. It can use the name
attribute to specify a slot name, and when no name is specified, it will render the default slot. Additional attributes passed to the slot element will be passed as slot props to the scoped slot defined in the parent.
Example:
<template> <div> <slot name="header"></slot> <slot></slot> <slot name="footer"></slot> </div> </template>
<template>
The <template>
element is used as a placeholder when you want to use a built-in directive without rendering an element in the DOM. The special handling for <template>
is only triggered if it is used with one of these directives: v-if
, v-else-if
, v-else
, v-for
, or v-slot
. If none of those directives are present, it will be rendered as a native <template>
element instead.
Example:
- Using
<template>
withv-if
,v-else-if
, orv-else
:<template v-if="condition1"> <div>Condition 1 is true</div> </template> <template v-else-if="condition2"> <div>Condition 2 is true</div> </template> <template v-else> <div>Both conditions are false</div> </template>
- Using
<template>
withv-for
:<template v-for="(item, index) in items" :key="index"> <div>{{ item }}</div> </template>
By understanding the usage and purpose of these built-in special elements, you can create more dynamic and flexible components in your Vue.js applications.
Getting Elements Using the ref
Attribute
To get a reference to a specific DOM element or Vue.js component instance, you can use the ref
attribute. Follow these steps:
- Add the
ref
attribute to an element: In your template, add theref
attribute with a unique name to the desired element.<input ref="myInput" type="text" placeholder="Enter your name" />
- Access the element using
$refs
object: In your Vue.js instance or component, you can access the element by referring to the$refs
object followed by the unique name you assigned earlier.methods: { focusInput() { this.$refs.myInput.focus(); }, },
Getting Elements Using the $refs
Object
Once you have assigned a ref
attribute to an element, you can access it using the $refs
object. Here’s a step-by-step example:
- Create a button to trigger a method: In your template, create a button with a
v-on:click
directive to call a method, likefocusInput
.<button @click="focusInput">Focus the input field</button>
- Define the method in your Vue.js instance or component: In your
methods
object, define thefocusInput
method to access the element using the$refs
object and perform an action, such as focusing the input field.
methods: { focusInput() { this.$refs.myInput.focus(); }, },
Common Use Cases and Best Practices for Getting Elements in Vue.js
- Focusing input fields: Use the
ref
attribute and$refs
object to set focus on a specific input field when needed, like when a modal opens or after a validation error. - Integrating third-party libraries: Some third-party libraries might require direct access to DOM elements. In such cases, you can use the
ref
attribute and$refs
object to get the required elements and pass them to the library’s API. - Animating elements: You might need to access specific elements to apply animations or transitions. The `ref
attribute and
$refs` object can help you target the elements you need to animate.
- Avoid overusing
$refs
: While$refs
can be very useful, it’s important not to overuse it. Vue.js encourages a more reactive data-driven approach, so try to keep direct DOM manipulation to a minimum. - Use
ref
only on elements that require direct manipulation: Use theref
attribute only on elements that require direct manipulation, like input fields, canvas elements, or when integrating with external libraries. - Do not rely on
$refs
for reactive data: Keep in mind that$refs
are not reactive, meaning that Vue.js won’t automatically update your template if a referenced element changes. Instead, use Vue.js’ reactive data properties and computed properties to handle updates.
By understanding how to work with elements in Vue.js and using the ref
attribute and $refs
object effectively, you can build more interactive and dynamic applications. Be sure to follow best practices and use these techniques judiciously to create maintainable and performant applications.
Introduction to Element UI
Element UI is a popular UI library for Vue.js that offers a wide range of reusable components and features for creating consistent and responsive web applications. With its robust set of components, Element UI simplifies the development process and helps developers create visually appealing applications more efficiently.
What is Element UI?
Element UI is a comprehensive UI toolkit specifically designed for Vue.js applications. It provides a rich set of ready-to-use components, such as buttons, forms, tables, dialogs, and more, allowing developers to build elegant and functional user interfaces with minimal effort. Element UI is highly customizable, enabling developers to easily adapt the components to fit their application’s design and requirements.
Example:
To use a basic Element UI button component in your Vue.js application, you would simply add the following code:
<el-button type="primary">Primary Button</el-button>
Benefits of using Element UI with Vue.js
There are several advantages to using Element UI with Vue.js, some of which include:
- Ease of use: Element UI components are designed to work seamlessly with Vue.js, making it easy for developers to integrate them into their applications.
- Consistent design: Element UI provides a consistent look and feel across all components, ensuring a cohesive user experience throughout your application.
- Customizability: Element UI components can be easily customized to match your application’s design and branding.
- Time-saving: By using pre-built components, developers can save time and effort, focusing on building features and functionality instead of designing UI components from scratch.
- Responsive design: Element UI components are built with responsive design in mind, ensuring that your application looks great on various devices and screen sizes.
- Extensive documentation: Element UI offers comprehensive documentation, including detailed guides and examples, making it easy for developers to learn and implement its components.
Installing and setting up Element UI
To start using Element UI in your Vue.js project, follow these step-by-step instructions:
- Install Element UI: First, install Element UI using npm or yarn:
npm install element-plus --save
or
yarn add element-plus
- Import Element UI in your Vue.js project: In your
main.js
ormain.ts
file, import Element UI and register it as a plugin:import { createApp } from "vue"; import ElementPlus from "element-plus"; import "element-plus/lib/theme-chalk/index.css"; import App from "./App.vue"; const app = createApp(App); app.use(ElementPlus); app.mount("#app");
This will make all Element UI components available throughout your application
- Use Element UI components in your application: Now, you can start using Element UI components in your Vue.js components. For example, to add a button, simply include the following code in your template:
<el-button type="primary">Click me</el-button>
By following these instructions, you should now have Element UI set up and ready to use in your Vue.js application. Explore the extensive documentation and examples provided by Element UI to make the most of its powerful components and features, and create elegant, responsive, and functional user interfaces for your web applications.
Exploring Element UI Components
Element UI is a popular UI toolkit for Vue.js developers. It offers a wide range of customizable components and features to make your web development process easier and faster. Let’s explore some of the key components in Element UI.
Overview of Element UI Components
Element UI has a vast collection of components that are categorized into various sections, including Basic, Form, Data, Navigation, and others. Here’s a comparison table of some of the popular components and their features.
Component | Features | Examples |
---|---|---|
Button | Different sizes, types, and shapes | Primary, Success, Info, Warning, Danger |
Input | Validation, clearable, password visibility toggle | Text, Number, Email, Password |
Select | Searchable, multiple selection, custom templates | Basic, Multiple, Tags, Remote |
Checkbox | Indeterminate state, disabled, custom templates | Basic, Group, Button, Remote |
Radio | Vertical/horizontal display, disabled, custom CSS | Basic, Group, Button, Remote |
Table | Sortable, filterable, pagination, expandable rows | Basic, Border, Stripe, Fixed |
Form | Validation, inline, custom layouts | Basic, Inline, Rules, Dynamic |
Dialog | Modal, alert, confirm, custom templates | Basic, Modal, Alert, Confirm |
Tooltip | Hover/click trigger, custom themes, positions | Basic, Content, Theme, Position |
Popover | Hover/click trigger, custom themes, positions | Basic, Content, Theme, Position |
Carousel | Autoplay, vertical/horizontal display, indicators | Basic, Card, Custom, Sync |
In this guide, we will discuss the different navigation components such as Menu, Tabs, and Breadcrumb that help users navigate through your website effectively.
Menu
A menu is a navigation component that provides a list of options for users to choose from. Menus can be organized vertically or horizontally, and can have submenus for a more organized navigation experience.
- Top bar: Top bar menus are horizontal menus that can be used in various scenarios. By default, the menu is vertical, but you can change it to horizontal by setting the
mode
prop to'horizontal'
. You can also customize the menu colors using thebackground-color
,text-color
, andactive-text-color
attributes.
Here’s an example of a horizontal top bar menu with two different color schemes:
<!-- Default colors --> <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect"> <!-- Menu items go here --> </el-menu> <!-- Custom colors --> <el-menu :default-active="activeIndex2" class="el-menu-demo" mode="horizontal" @select="handleSelect" background-color="#545c64" text-color="#fff" active-text-color="#ffd04b"> <!-- Menu items go here --> </el-menu>
- Side bar: Vertical menus with sub-menus can be used as sidebars for navigation. You can create menu groups using the
el-menu-item-group
component, and customize the colors in a similar way as the top bar menu.
Here’s an example of a sidebar with default and custom colors:
<!-- Default colors --> <el-menu default-active="2" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose"> <!-- Menu items and submenus go here --> </el-menu> <!-- Custom colors --> <el-menu default-active="2" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose" background-color="#545c64" text-color="#fff" active-text-color="#ffd04b"> <!-- Menu items and submenus go here --> </el-menu>
Tabs are a great way to divide data collections that are related yet belong to different types. In this guide, we will go through various usage patterns and customization options for tabs.
Basic Usage
Tabs provide a selective card functionality. By default, the first tab is selected as active, and you can activate any tab by setting the value attribute.
Here’s a basic example of tabs:
<template> <el-tabs v-model="activeName" @tab-click="handleClick"> <el-tab-pane label="User" name="first">User</el-tab-pane> <el-tab-pane label="Config" name="second">Config</el-tab-pane> <el-tab-pane label="Role" name="third">Role</el-tab-pane> <el-tab-pane label="Task" name="fourth">Task</el-tab-pane> </el-tabs> </template> <script> export default { data() { return { activeName: 'first' }; }, methods: { handleClick(tab, event) { console.log(tab, event); } } }; </script>
Card Style
You can style your tabs as cards by setting the type
attribute to "card"
:
<template> <el-tabs type="card" @tab-click="handleClick"> <el-tab-pane label="User">User</el-tab-pane> <el-tab-pane label="Config">Config</el-tab-pane> <el-tab-pane label="Role">Role</el-tab-pane> <el-tab-pane label="Task">Task</el-tab-pane> </el-tabs> </template> <script> export default { data() { return { activeName: 'first' }; }, methods: { handleClick(tab, event) { console.log(tab, event); } } }; </script>
Border Card
For border card tabs, set the type
attribute to "border-card"
:
<el-tabs type="border-card"> <el-tab-pane label="User">User</el-tab-pane> <el-tab-pane label="Config">Config</el-tab-pane> <el-tab-pane label="Role">Role</el-tab-pane> <el-tab-pane label="Task">Task</el-tab-pane> </el-tabs>
Tab Position
You can use the tab-position
attribute to set the tab’s position. You can choose from four directions: "left"
, "right"
, "top"
, and "bottom"
.
<template> <el-radio-group v-model="tabPosition" style="margin-bottom: 30px;"> <el-radio-button label="top">top</el-radio-button> <el-radio-button label="right">right</el-radio-button> <el-radio-button label="bottom">bottom</el-radio-button> <el-radio-button label="left">left</el-radio-button> </el-radio-group> <el-tabs :tab-position="tabPosition" style="height: 200px;"> <el-tab-pane label="User">User</el-tab-pane> <el-tab-pane label="Config">Config</el-tab-pane> <el-tab-pane label="Role">Role</el-tab-pane> <el-tab-pane label="Task">Task</el-tab-pane> </el-tabs> </template> <script> export default { data() { return { tabPosition: 'left' }; } }; </script>
Custom Tab
You can use named slots to customize the tab label content. Here’s an example of using a custom icon in the tab label:
<el-tabs type="border-card"> <el-tab-pane> <span slot="label"><i class="el-icon-date"></i> Route</span> Route </el-tab-pane> <el-tab-pane label="Config">Config</el-tab-pane> <el-tab-pane label="Role">Role</el-tab-pane> <el-tab-pane label="Task">Task</el-tab-pane> </el-tabs>
Add & Close Tab
Only card type tabs support the addable
and closeable
functionality. Here’s an example of how to add and remove tabs:
<el-tabs v-model="editableTabsValue" type="card" editable @edit="handleTabsEdit"> <el-tab-pane v-for="(item, index) in editableTabs" :key="item.name" :label="item.title" :name="item.name" > {{item.content}} </el-tab-pane> </el-tabs> <script> export default { data() { return { editableTabsValue: '2', editableTabs: [{ title: 'Tab 1', name: '1', content: 'Tab 1 content' }, { title: 'Tab 2', name: '2', content: 'Tab 2 content' }], tabIndex: 2 } }, methods: { handleTabsEdit(targetName, action) { if (action === 'add') { let newTabName = ++this.tabIndex + ''; this.editableTabs.push({ title: 'New Tab', name: newTabName, content: 'New Tab content' }); this.editableTabsValue = newTabName; } if (action === 'remove') { let tabs = this.editableTabs; let activeName = this.editableTabsValue; if (activeName === targetName) { tabs.forEach((tab, index) => { if (tab.name === targetName) { let nextTab = tabs[index + 1] || tabs[index - 1]; if (nextTab) { activeName = nextTab.name; } } }); } this.editableTabsValue = activeName; this.editableTabs = tabs.filter(tab => tab.name !== targetName); } } } } </script>
Customized Trigger Button for New Tab
You can also create a custom button to add new tabs:
<div style="margin-bottom: 20px;"> <el-button size="small" @click="addTab(editableTabsValue)" > add tab </el-button> </div> <el-tabs v-model="editableTabsValue" type="card" closable @tab-remove="removeTab"> <el-tab-pane v-for="(item, index) in editableTabs" :key="item.name" :label="item.title" :name="item.name" > {{item.content}} </el-tab-pane> </el-tabs> <script> export default { data() { return { editableTabsValue: '2', editableTabs: [{ title: 'Tab 1', name: '1', content: 'Tab 1 content' }, { title: 'Tab 2', name: '2', content: 'Tab 2 content' }], tabIndex: 2 } }, methods: { addTab(targetName) { let newTabName = ++this.tabIndex + ''; this.editableTabs.push({ title: 'New Tab', name: newTabName, content: 'New Tab content' }); this.editableTabsValue = newTabName; }, removeTab(targetName) { let tabs = this.editableTabs; let activeName = this.editableTabsValue; if (activeName === targetName) { tabs.forEach((tab, index) => { if (tab.name === targetName) { let nextTab = tabs[index + 1] || tabs[index - 1]; if (nextTab) { activeName = nextTab.name; } } }); } this.editableTabsValue = activeName; this.editableTabs = tabs.filter(tab => tab.name !== targetName); } } } </script>
A breadcrumb is a useful navigation component that displays the location of the current page, making it easier for users to browse back through the hierarchy of pages.
Basic Usage
A breadcrumb is composed of several levels, starting from the homepage. In
el-breadcrumb
, each el-breadcrumb-item
represents a level. The component has a separator
attribute, which determines the separator character between levels. Its default value is /
.
<el-breadcrumb separator="/"> <el-breadcrumb-item :to="{ path: '/' }">homepage</el-breadcrumb-item> <el-breadcrumb-item><a href="/">promotion management</a></el-breadcrumb-item> <el-breadcrumb-item>promotion list</el-breadcrumb-item> <el-breadcrumb-item>promotion detail</el-breadcrumb-item> </el-breadcrumb>
Icon Separator
You can use an icon as the separator by setting the separator-class
attribute. This will override the default separator.
<el-breadcrumb separator-class="el-icon-arrow-right"> <el-breadcrumb-item :to="{ path: '/' }">homepage</el-breadcrumb-item> <el-breadcrumb-item>promotion management</el-breadcrumb-item> <el-breadcrumb-item>promotion list</el-breadcrumb-item> <el-breadcrumb-item>promotion detail</el-breadcrumb-item> </el-breadcrumb>
Breadcrumb Attributes
The el-breadcrumb
component has the following attributes:
separator
: The separator character (default:/
).separator-class
: The class name of the icon separator.
Breadcrumb Item Attributes
The el-breadcrumb-item
component has the following attributes:
to
: The target route of the link, which works the same as theto
attribute in Vue Router (default: not set).replace
: If set totrue
, the navigation will not leave a history record (default:false
).
By using breadcrumbs in your web application, you can help users navigate through pages with ease and provide a clear representation of the page hierarchy.
If the path of the page is simple, it is recommended to use the PageHeader
component instead of the Breadcrumb
. The PageHeader
component provides a clean and straightforward way to display the current page’s title and a back button.
Basic Usage
To create a basic
PageHeader
, use the el-page-header
component and specify the content. You can also handle the back button click by listening to the back
event.
<el-page-header @back="goBack" content="detail"> </el-page-header> <script> export default { methods: { goBack() { console.log('go back'); } } } </script>
Attributes
The el-page-header
component has the following attributes:
title
: The main title (default: “Back”).content
: The content displayed in the header (default: not set).
Events
The el-page-header
component has the following event:
back
: Triggers when the back button is clicked.
Slots
The el-page-header
component provides the following slots:
title
: A slot for customizing the title content.content
: A slot for customizing the content displayed in the header.
By using the PageHeader
component in your web application, you can provide a simple and effective way for users to navigate back to the previous page and display the current page’s title.
The Dropdown
component allows you to create toggleable menus for displaying lists of links and actions. This is especially useful when you need to save space in your application’s user interface.
Basic Usage
To create a basic Dropdown
, use the el-dropdown
component. The triggering element is rendered by the default slot, and the dropdown part is rendered by the slot named dropdown
. By default, the dropdown list shows when you hover on the triggering element without having to click it.
<el-dropdown> <span class="el-dropdown-link"> Dropdown List<i class="el-icon-arrow-down el-icon--right"></i> </span> <el-dropdown-menu slot="dropdown"> <el-dropdown-item>Action 1</el-dropdown-item> <el-dropdown-item>Action 2</el-dropdown-item> <el-dropdown-item>Action 3</el-dropdown-item> <el-dropdown-item disabled>Action 4</el-dropdown-item> <el-dropdown-item divided>Action 5</el-dropdown-item> </el-dropdown-menu> </el-dropdown> <style> .el-dropdown-link { cursor: pointer; color: #409EFF; } .el-icon-arrow-down { font-size: 12px; } </style>
Triggering Element
You can use a button to trigger the dropdown list by using the el-button
component. Use the split-button
attribute to split the triggering element into a button group with the left button being a normal button and the right one the actual triggering target.
<el-dropdown> <el-button type="primary"> Dropdown List<i class="el-icon-arrow-down el-icon--right"></i> </el-button> <el-dropdown-menu slot="dropdown"> <el-dropdown-item>Action 1</el-dropdown-item> <el-dropdown-item>Action 2</el-dropdown-item> <el-dropdown-item>Action 3</el-dropdown-item> <el-dropdown-item>Action 4</el-dropdown-item> <el-dropdown-item>Action 5</el-dropdown-item> </el-dropdown-menu> </el-dropdown> <el-dropdown split-button type="primary" @click="handleClick"> Dropdown List <el-dropdown-menu slot="dropdown"> <el-dropdown-item>Action 1</el-dropdown-item> <el-dropdown-item>Action 2</el-dropdown-item> <el-dropdown-item>Action 3</el-dropdown-item> <el-dropdown-item>Action 4</el-dropdown-item> <el-dropdown-item>Action 5</el-dropdown-item> </el-dropdown-menu> </el-dropdown> <style> .el-dropdown { vertical-align: top; } .el-dropdown + .el-dropdown { margin-left: 15px; } .el-icon-arrow-down { font-size: 12px; } </style> <script> export default { methods: { handleClick() { alert('button click'); } } } </script>
How to Trigger
By default, the dropdown list is triggered by hovering over the triggering element. You can change the trigger behavior to a click event by setting the trigger
attribute to "click"
.
<el-row class="block-col-2"> <el-col :span="12"> <span class="demonstration">hover to trigger</span> <el-dropdown> <span class="el-dropdown-link"> Dropdown List<i class="el-icon-arrow-down el-icon--right"></i> </span> <el-dropdown-menu slot="dropdown"> <el-dropdown-item icon="el-icon-plus">Action 1</el-dropdown-item> <el-dropdown-item icon="el-icon-circle-plus">Action 2</el-dropdown-item> <el-dropdown-item icon="el-icon-circle-plus-outline">Action 3</el-dropdown-item> <el-dropdown-item icon="el-icon-check">Action 4</el-dropdown-item> <el-dropdown-item icon="el-icon-circle-check">Action 5</el-dropdown-item> </el-dropdown-menu> </el-dropdown> </el-col> <el-col :span="12"> <span class="demonstration">click to trigger</span> <el-dropdown trigger="click"> <span class="el-dropdown-link"> Dropdown List<i class="el-icon-arrow-down el-icon--right"></i> </span> <el-dropdown-menu slot="dropdown"> <el-dropdown-item icon="el-icon-plus">Action 1</el-dropdown-item> <el-dropdown-item icon="el-icon-circle-plus">Action 2</el-dropdown-item> <el-dropdown-item icon="el-icon-circle-plus-outline">Action 3</el-dropdown-item> <el-dropdown-item icon="el-icon-check">Action 4</el-dropdown-item> <el-dropdown-item icon="el-icon-circle-check">Action 5</el-dropdown-item> </el-dropdown-menu> </el-dropdown> </el-col> </el-row> <style> .el-dropdown-link { cursor: pointer; color: #409EFF; } .el-icon-arrow-down { font-size: 12px; } .demonstration { display: block; color: #8492a6; font-size: 14px; margin-bottom: 20px; } </style>
Command Event
Clicking each dropdown item fires an event whose parameter is assigned by each item. You can listen to this event using the @command
directive.
<el-dropdown @command="handleCommand"> <span class="el-dropdown-link"> Dropdown List<i class="el-icon-arrow-down el-icon--right"></i> </span> <el-dropdown-menu slot="dropdown"> <el-dropdown-item command="a">Action 1</el-dropdown-item> <el-dropdown-item command="b">Action 2</el-dropdown-item> <el-dropdown-item command="c">Action 3</el-dropdown-item> <el-dropdown-item command="d" disabled>Action 4</el-dropdown-item> <el-dropdown-item command="e" divided>Action 5</el-dropdown-item> </el-dropdown-menu> </el-dropdown> <style> .el-dropdown-link { cursor: pointer; color: #409EFF; } .el-icon-arrow-down { font-size: 12px; } </style> <script> export default { methods: { handleCommand(command) { this.$message('click on item ' + command); } } } </script>
Sizes
Besides the default size, the Dropdown
component provides three additional sizes for different scenarios: medium
, small
, and mini
. Use the size
attribute to set the desired size.
<el-dropdown split-button type="primary"> Default <el-dropdown-menu slot="dropdown"> <el-dropdown-item>Action 1</el-dropdown-item> <el-dropdown-item>Action 2</el-dropdown-item> <el-dropdown-item>Action 3</el-dropdown-item> <el-dropdown-item>Action 4</el-dropdown-item> </el-dropdown-menu> </el-dropdown> <el-dropdown size="medium" split-button type="primary"> Medium <el-dropdown-menu slot="dropdown"> <el-dropdown-item>Action 1</el-dropdown-item> <el-dropdown-item>Action 2</el-dropdown-item> <el-dropdown-item>Action 3</el-dropdown-item> <el-dropdown-item>Action 4</el-dropdown-item> </el-dropdown-menu> </el-dropdown> <el-dropdown size="small" split-button type="primary"> Small <el-dropdown-menu slot="dropdown"> <el-dropdown-item>Action 1</el-dropdown-item> <el-dropdown-item>Action 2</el-dropdown-item> <el-dropdown-item>Action 3</el-dropdown-item> <el-dropdown-item>Action 4</el-dropdown-item> </el-dropdown-menu> </el-dropdown> <el-dropdown size="mini" split-button type="primary"> Mini <el-dropdown-menu slot="dropdown"> <el-dropdown-item>Action 1</el-dropdown-item> <el-dropdown-item>Action 2</el-dropdown-item> <el-dropdown-item>Action 3</el-dropdown-item> <el-dropdown-item>Action 4</el-dropdown-item> </el-dropdown-menu> </el-dropdown>
Form components (Input, Radio, Checkbox, etc.)
Input
The Input
component is used for capturing text input from users. It can be customized to handle different types of input, such as text, numbers, or even passwords.
Basic Usage:
<el-input placeholder="Please input" v-model="input"></el-input> <script> export default { data() { return { input: '' } } } </script>
Radio
The Radio
component allows users to select a single option from a list of choices. It’s an excellent choice for situations where you need to provide multiple options but only want users to choose one.
Basic Usage:
<template> <el-radio v-model="radio" label="1">Option A</el-radio> <el-radio v-model="radio" label="2">Option B</el-radio> </template> <script> export default { data () { return { radio: '1' }; } } </script>
Checkbox
The Checkbox
component allows users to select multiple options from a list of choices. It’s perfect for situations where you need to provide multiple options and let users choose as many as they want.
Basic Usage:
<template> <!-- `checked` should be true or false --> <el-checkbox v-model="checked">Option</el-checkbox> </template> <script> export default { data() { return { checked: true }; } }; </script>
Data components (Table, Tag, Tree, etc.)
Table
The Table
component allows you to display data in a tabular format. It’s perfect for organizing and presenting data in rows and columns.
Basic Usage:
<template> <el-table :data="tableData" style="width: 100%"> <el-table-column prop="date" label="Date" width="180"> </el-table-column> <el-table-column prop="name" label="Name" width="180"> </el-table-column> <el-table-column prop="address" label="Address"> </el-table-column> </el-table> </template> <script> export default { data() { return { tableData: [{ date: '2016-05-03', name: 'Tom', address: 'No. 189, Grove St, Los Angeles' }, { date: '2016-05-02', name: 'Tom', address: 'No. 189, Grove St, Los Angeles' }, { date: '2016-05-04', name: 'Tom', address: 'No. 189, Grove St, Los Angeles' }, { date: '2016-05-01', name: 'Tom', address: 'No. 189, Grove St, Los Angeles' }] } } } </script>
Tag
The Tag
component is used for categorizing and labeling content. It’s useful for displaying metadata or other relevant information.
Basic Usage:
<span class="tag">Important</span>
Progress
The Progress
component visualizes the progress of a task or operation. It’s great for showing users how much of a task has been completed.
Basic Usage:
<el-progress :percentage="50"></el-progress> <el-progress :percentage="100" :format="format"></el-progress> <el-progress :percentage="100" status="success"></el-progress> <el-progress :percentage="100" status="warning"></el-progress> <el-progress :percentage="50" status="exception"></el-progress> <script> export default { methods: { format(percentage) { return percentage === 100 ? 'Full' : `${percentage}%`; } } }; </script>
Tree
The Tree
component is used to display hierarchical data in a tree-like structure. It’s perfect for organizing data with parent-child relationships.
Basic Usage:
<el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick"></el-tree> <script> export default { data() { return { data: [{ label: 'Level one 1', children: [{ label: 'Level two 1-1', children: [{ label: 'Level three 1-1-1' }] }] }, { label: 'Level one 2', children: [{ label: 'Level two 2-1', children: [{ label: 'Level three 2-1-1' }] }, { label: 'Level two 2-2', children: [{ label: 'Level three 2-2-1' }] }] }, { label: 'Level one 3', children: [{ label: 'Level two 3-1', children: [{ label: 'Level three 3-1-1' }] }, { label: 'Level two 3-2', children: [{ label: 'Level three 3-2-1' }] }] }], defaultProps: { children: 'children', label: 'label' } }; }, methods: { handleNodeClick(data) { console.log(data); } } }; </script>
Pagination
The Pagination
component enables you to split large data sets into smaller chunks, making it easier for users to navigate through the data.
Basic Usage:
<div class="block"> <span class="demonstration">When you have few pages</span> <el-pagination layout="prev, pager, next" :total="50"> </el-pagination> </div> <div class="block"> <span class="demonstration">When you have more than 7 pages</span> <el-pagination layout="prev, pager, next" :total="1000"> </el-pagination> </div>
Badge
The Badge
component is a small, circular element used for displaying notifications, counters, or statuses.
Basic Usage:
<el-badge :value="12" class="item"> <el-button size="small">comments</el-button> </el-badge> <el-badge :value="3" class="item"> <el-button size="small">replies</el-button> </el-badge> <el-badge :value="1" class="item" type="primary"> <el-button size="small">comments</el-button> </el-badge> <el-badge :value="2" class="item" type="warning"> <el-button size="small">replies</el-button> </el-badge> <el-dropdown trigger="click"> <span class="el-dropdown-link"> Click Me<i class="el-icon-caret-bottom el-icon--right"></i> </span> <el-dropdown-menu slot="dropdown"> <el-dropdown-item class="clearfix"> comments <el-badge class="mark" :value="12" /> </el-dropdown-item> <el-dropdown-item class="clearfix"> replies <el-badge class="mark" :value="3" /> </el-dropdown-item> </el-dropdown-menu> </el-dropdown> <style> .item { margin-top: 10px; margin-right: 40px; } </style>
Skeleton
The Skeleton
component is a placeholder used to show the loading state of content. It’s perfect for improving the perceived performance of your application.
Basic Usage:
<template> <el-skeleton /> </template>
Empty
The Empty
component is used to display a message when there’s no data to show. It’s great for providing helpful feedback to users.
Basic Usage:
<el-empty description="description"></el-empty>
Descriptions
The Descriptions
component is used to display a list of descriptions, making it easy to present key-value pairs of information.
Basic Usage:
<el-descriptions title="User Info"> <el-descriptions-item label="Username">kooriookami</el-descriptions-item> <el-descriptions-item label="Telephone">18100000000</el-descriptions-item> <el-descriptions-item label="Place">Suzhou</el-descriptions-item> <el-descriptions-item label="Remarks"> <el-tag size="small">School</el-tag> </el-descriptions-item> <el-descriptions-item label="Address">No.1188, Wuzhong Avenue, Wuzhong District, Suzhou, Jiangsu Province</el-descriptions-item> </el-descriptions>
Result
The Result
component is used to display the result of an operation, such as success, error, or information messages.
Basic Usage:
<el-row> <el-col :sm="12" :lg="6"> <el-result icon="success" title="Success Tip" subTitle="Please follow the instructions"> <template slot="extra"> <el-button type="primary" size="medium">Back</el-button> </template> </el-result> </el-col> <el-col :sm="12" :lg="6"> <el-result icon="warning" title="Warning Tip" subTitle="Please follow the instructions"> <template slot="extra"> <el-button type="primary" size="medium">Back</el-button> </template> </el-result> </el-col> <el-col :sm="12" :lg="6"> <el-result icon="error" title="Error Tip" subTitle="Please follow the instructions"> <template slot="extra"> <el-button type="primary" size="medium">Back</el-button> </template> </el-result> </el-col> <el-col :sm="12" :lg="6"> <el-result icon="info" title="Info Tip" subTitle="Please follow the instructions"> <template slot="extra"> <el-button type="primary" size="medium">Back</el-button> </template> </el-result> </el-col> </el-row>
Notice components are a crucial part of user interface design. They provide feedback to users on the state of the system, allowing users to understand how to interact with the application. Notice components include alert, progress, table, tag, tree, pagination, badge, skeleton, empty, descriptions, and result. In this text, we will discuss alert components.
Alert Components
Alert components are used to display important alert messages. They are non-overlay elements on the page that do not disappear automatically. Alert components provide four types of themes defined by type, whose default value is info. These four themes are success alert, info alert, warning alert, and error alert.
Basic Usage of Alert Components
To use the alert component, you need to define its type and title. The type defines the theme of the alert component, and the title is the message displayed in the component. Here is an example of how to use alert components:
<template> <el-alert title="success alert" type="success"> </el-alert> <el-alert title="info alert" type="info"> </el-alert> <el-alert title="warning alert" type="warning"> </el-alert> <el-alert title="error alert" type="error"> </el-alert> </template>
Alert Component Themes
Alert components provide two different themes, light and dark. The default is light. To change the theme of the alert component, you can set the effect attribute. Here is an example of how to set the effect to change the theme:
<template> <el-alert title="success alert" type="success" effect="dark"> </el-alert> <el-alert title="info alert" type="info" effect="dark"> </el-alert> <el-alert title="warning alert" type="warning" effect="dark"> </el-alert> <el-alert title="error alert" type="error" effect="dark"> </el-alert> </template>
Customizable Close Button
Alert components allow you to configure if they are closable or not. You can also customize the close button text and closing callbacks. To make an alert component unclosable, you can set the closable attribute to false. Here is an example of how to create an unclosable alert component:
<template> <el-alert title="unclosable alert" type="success" :closable="false"> </el-alert> <el-alert title="customized close-text" type="info" close-text="Gotcha"> </el-alert> <el-alert title="alert with callback" type="warning" @close="hello"> </el-alert> </template> <script> export default { methods: { hello() { alert('Hello World!'); } } } </script>
To customize the close button text, you can set the close-text attribute to replace the default cross symbol. The close-text attribute must be a string. Here is an example of how to create an alert component with a customized close button text:
Notification
Element has registered the $notify
method and it receives an object as its parameter. In the simplest case, you can set the title
field and themessage
field for the title and body of the notification. By default, the notification automatically closes after 4500ms, but by setting duration
you can control its duration. Specifically, if set to , it will not close automatically. Note that
duration
receives a Number
in milliseconds.
<template> <el-button plain @click="open1"> Closes automatically </el-button> <el-button plain @click="open2"> Won't close automatically </el-button> </template> <script> export default { methods: { open1() { const h = this.$createElement; this.$notify({ title: 'Title', message: h('i', { style: 'color: teal' }, 'This is a reminder') }); }, open2() { this.$notify({ title: 'Prompt', message: 'This is a message that does not automatically close', duration: 0 }); } } } </script>
Notification components display global notification messages at a corner of the page. They can be customized by:
title
: The title of the notification message.message
: A text string that provides the notification message.type
: The type of the notification message (success, warning, info, error).position
: The position of the notification message (top-right, top-left, bottom-right, bottom-left).duration
: The duration before the notification automatically closes.dangerouslyUseHTMLString
: A boolean that allows the use of HTML strings in the notification message.showClose
: A boolean that determines whether the notification can be closed or not.
MessageBox
MessageBox components display a message box with an optional title, message, and buttons. They can be customized by:
title
: The title of the message box.message
: A text string that provides the message of the message box.type
: The type of the message box (success, warning, info, error).showCancelButton
: A boolean that determines whether to display a cancel button.confirmButtonText
: The text of the confirm button.cancelButtonText
: The text of the cancel button.
Miscellaneous components (Tooltip, Popover, Carousel, etc.)
Element UI provides a range of miscellaneous components, including Tooltip, Popover, and Carousel.
Tooltip
Use attribute content
to set the display content when hover. The attribute placement
determines the position of the tooltip. Its value is [orientation]-[alignment]
with four orientations top
, left
, right
, bottom
and three alignments start
, end
, null
, and the default alignment is null. Take placement="left-end"
for example, Tooltip will display on the left of the element which you are hovering and the bottom of the tooltip aligns with the bottom of the element.
<div class="box"> <div class="top"> <el-tooltip class="item" effect="dark" content="Top Left prompts info" placement="top-start"> <el-button>top-start</el-button> </el-tooltip> <el-tooltip class="item" effect="dark" content="Top Center prompts info" placement="top"> <el-button>top</el-button> </el-tooltip> <el-tooltip class="item" effect="dark" content="Top Right prompts info" placement="top-end"> <el-button>top-end</el-button> </el-tooltip> </div> <div class="left"> <el-tooltip class="item" effect="dark" content="Left Top prompts info" placement="left-start"> <el-button>left-start</el-button> </el-tooltip> <el-tooltip class="item" effect="dark" content="Left Center prompts info" placement="left"> <el-button>left</el-button> </el-tooltip> <el-tooltip class="item" effect="dark" content="Left Bottom prompts info" placement="left-end"> <el-button>left-end</el-button> </el-tooltip> </div> <div class="right"> <el-tooltip class="item" effect="dark" content="Right Top prompts info" placement="right-start"> <el-button>right-start</el-button> </el-tooltip> <el-tooltip class="item" effect="dark" content="Right Center prompts info" placement="right"> <el-button>right</el-button> </el-tooltip> <el-tooltip class="item" effect="dark" content="Right Bottom prompts info" placement="right-end"> <el-button>right-end</el-button> </el-tooltip> </div> <div class="bottom"> <el-tooltip class="item" effect="dark" content="Bottom Left prompts info" placement="bottom-start"> <el-button>bottom-start</el-button> </el-tooltip> <el-tooltip class="item" effect="dark" content="Bottom Center prompts info" placement="bottom"> <el-button>bottom</el-button> </el-tooltip> <el-tooltip class="item" effect="dark" content="Bottom Right prompts info" placement="bottom-end"> <el-button>bottom-end</el-button> </el-tooltip> </div> </div> <style> .box { width: 400px; .top { text-align: center; } .left { float: left; width: 110px; } .right { float: right; width: 110px; } .bottom { clear: both; text-align: center; } .item { margin: 4px; } .left .el-tooltip__popper, .right .el-tooltip__popper { padding: 8px 10px; } .el-button { width: 110px; } } </style>
Tooltip components provide additional information when the user hovers over an element. They can be customized by:
content
: The content of the tooltip.placement
: The placement of the tooltip (top, bottom, left, right).disabled
: A boolean that determines whether the tooltip is disabled or not.
Popover
The trigger
attribute is used to define how popover is triggered: hover
, click
, focus
or manual
. As for the triggering element, you can write it in two different ways: use the slot="reference"
named slot, or use the v-popover
directive and set it to Popover’s ref
.
<template> <el-popover placement="top-start" title="Title" width="200" trigger="hover" content="this is content, this is content, this is content"> <el-button slot="reference">Hover to activate</el-button> </el-popover> <el-popover placement="bottom" title="Title" width="200" trigger="click" content="this is content, this is content, this is content"> <el-button slot="reference">Click to activate</el-button> </el-popover> <el-popover ref="popover" placement="right" title="Title" width="200" trigger="focus" content="this is content, this is content, this is content"> </el-popover> <el-button v-popover:popover>Focus to activate</el-button> <el-popover placement="bottom" title="Title" width="200" trigger="manual" content="this is content, this is content, this is content" v-model="visible"> <el-button slot="reference" @click="visible = !visible">Manual to activate</el-button> </el-popover> </template> <script> export default { data() { return { visible: false }; } }; </script>
Popover components display additional information when the user clicks on an element. They can be customized by:
title
: The title of the popover.content
: The content of the popover.placement
: The placement of the popover (top, bottom, left, right).trigger
: The event that triggers the popover (click, hover, focus).disabled
: A boolean that determines whether the popover is disabled or not.
Carousel
Combine el-carousel
with el-carousel-item
, and you’ll get a carousel. Content of each slide is completely customizable, and you just need to place it inside el-carousel-item
tag. By default the carousel switches when mouse hovers over an indicator. Set trigger
to click
, and the carousel switches only when an indicator is clicked.
<template> <div class="block"> <span class="demonstration">Switch when indicator is hovered (default)</span> <el-carousel height="150px"> <el-carousel-item v-for="item in 4" :key="item"> <h3 class="small">{{ item }}</h3> </el-carousel-item> </el-carousel> </div> <div class="block"> <span class="demonstration">Switch when indicator is clicked</span> <el-carousel trigger="click" height="150px"> <el-carousel-item v-for="item in 4" :key="item"> <h3 class="small">{{ item }}</h3> </el-carousel-item> </el-carousel> </div> </template> <style> .el-carousel__item h3 { color: #475669; font-size: 14px; opacity: 0.75; line-height: 150px; margin: 0; } .el-carousel__item:nth-child(2n) { background-color: #99a9bf; } .el-carousel__item:nth-child(2n+1) { background-color: #d3dce6; } </style>
Carousel components display a rotating series of images or other content. They can be customized by:
height
: The height of the carousel.initialIndex
: The index of the initial slide.interval
: The interval between each slide.arrow
: A boolean that determines whether to display arrows for slide navigation.indicatorPosition
: The position of the slide indicators (outside, none).autoplay
: A boolean that determines whether the carousel should autoplay.
Integrating Element UI with Vue.js
Element UI is a popular UI library that can be integrated with Vue.js to quickly create beautiful and responsive web applications. Here are the steps to get started with using Element UI in your Vue.js project:
Importing Element UI components into a Vue.js project
- Install Element UI using npm:
npm install element-ui --save
- Import the necessary Element UI components in your Vue.js project. For example, to import a button and a input component, add the following code in your main.js file:
import Vue from 'vue'; import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; import { Button, Input } from 'element-ui'; Vue.use(ElementUI); Vue.component(Button.name, Button); Vue.component(Input.name, Input);
Note that we first import the main Element UI library and its CSS styles. Then, we import specific components we need to use.
- Now you can use the imported components in your Vue.js application. For example, to use the button and input components in your template, add the following code:
<template> <div> <el-button>Click Me</el-button> <el-input placeholder="Enter your name"></el-input> </div> </template>
Registering Element UI components globally or locally
Element UI provides two ways to register components in your Vue.js application – globally and locally.
Registering Element UI components globally
To register the components globally, you can use the Vue.use()
method provided by Vue.js. This method allows you to install a plugin globally in your application.
First, you need to import the components you want to use in your main.js file:
import Vue from 'vue'; import { Button, Input } from 'element-ui';
Then, you can register the components globally using the Vue.use()
method:
Vue.use(Button); Vue.use(Input);
After registering the components, you can use them in any component without needing to import them again.
Registering Element UI components locally
To register the components locally, you need to import the components in the component where you want to use them. For example, to use the Button component in a component named MyButton
, you can add the following code:
import { Button } from 'element-ui'; export default { name: 'MyButton', components: { 'el-button': Button } }
Now you can use the Button component in your template as follows:
<template> <div> <el-button>Click Me</el-button> </div> </template>
When registering the components locally, you need to import and register them in each component where you want to use them.
Examples of using Element UI components in a Vue.js application
Element UI offers a wide range of components that can be used in a Vue.js application. Here are five examples of how you can use these components in your project:
- Using the Button component:
You can use the Button component to add a button to your Vue.js template. For example:
<template> <div> <el-button type="primary">Click Me</el-button> </div> </template>
- Using the Input component:
You can use the Input component to add an input field to your Vue.js template. For example:
<template> <div> <el-input placeholder="Enter your name"></el-input> </div> </template>
- Using the Dialog component:
You can use the Dialog component to create a modal dialog box in your Vue.js application. For example:
<template> <div> <el-button @click="showDialog">Open Dialog</el-button> <el-dialog :visible.sync="dialogVisible"> <span>This is a dialog box</span> <div slot="footer"> <el-button @click="dialogVisible = false">Cancel</el-button> <el-button type="primary" @click="dialogVisible = false">OK</el-button> </div> </el-dialog> </div> </template> <script> export default { data() { return { dialogVisible: false }; }, methods: { showDialog() { this.dialogVisible = true; } } } </script>
- Using the Notification component:
You can use the Notification component to display a notification message in your Vue.js application. For example:
<template> <div> <el-button @click="showNotification">Show Notification</el-button> </div> </template> <script> export default { methods: { showNotification() { this.$notify({ title: 'Notification Title', message: 'This is a notification message', type: 'success' }); } } } </script>
- Using the Table component:
You can use the Table component to display data in a table format in your Vue.js application. For example:
<template> <div> <el-table :data="tableData"> <el-table-column prop="name" label="Name"></el-table-column> <el-table-column prop="age" label="Age"></el-table-column> <el-table-column prop="address" label="Address"></el-table-column> </el-table> </div> </template> <script> export default { data() { return { tableData: [ { name: 'John Doe', age: 28, address: '123 Main St' }, { name: 'Jane Smith', age: 35, address: '456 Oak St' }, { name: 'Bob Johnson', age: 42, address: '789 Pine St' } ] }; } } </script>
These are just a few examples of how you can use Element UI components in your Vue.js application. The possibilities are endless, so feel free to explore and experiment with the various components that Element UI has to offer.
Customizing Element UI
Element UI is a highly customizable library that allows you to customize the look and feel of your application. In this guide, we’ll walk you through some of the ways you can customize Element UI to fit your specific needs.
Overview of Element UI theming
Theming is an essential part of customizing Element UI components. It allows you to modify the default color scheme, fonts, and other visual properties of the components to match your branding or design requirements.
Name | Default Value |
---|---|
Primary | #409EFF |
Success | #67C23A |
Warning | #E6A23C |
Danger | #F56C6C |
Info | #909399 |
Text | #303133 |
Border | #E4E7ED |
Background | #F5F7FA |
You can also modify the colors of specific components by setting the appropriate properties in your custom theme.
Modifying global Element UI variables for custom themes
To modify the global variables in Element UI, you need to override them in your custom theme. Here are the steps to create a custom theme:
- Create a new file named
element-variables.scss
in your project directory. - Copy the content of the
default
theme file fromnode_modules/element-ui/packages/theme-chalk/src/common/var.scss
intoelement-variables.scss
. - Modify the variables to your liking. For example, to change the primary color to red, set the
$--color-primary
variable to#FF0000
. - In your main SCSS file, import the modified variables before importing Element UI styles:
@import 'element-variables.scss'; @import '~element-ui/packages/theme-chalk/src/index';
- Build your project to generate the CSS file with the new styles.
Here is an example of modifying the primary color of the button component:
// element-variables.scss $--color-primary: #FF0000; // MyButton.vue <template> <el-button>Click Me</el-button> </template> <script> import 'element-ui/lib/theme-chalk/index.css'; export default { name: 'MyButton' } </script> <style scoped> @import 'element-variables.scss'; </style>
This will override the default primary color of the button component with your custom color.
By customizing the global variables, you can modify the appearance of multiple components at once, making it easier to maintain a consistent design throughout your application.
Creating custom styles for Element UI components
Creating custom styles for Element UI components can be a great way to give your application a unique look and feel that matches your brand or project. Element UI provides several ways to customize the default styles, from using the online Theme Roller to modifying global variables and creating a custom theme using the CLI theme tool.
Here are some ways to customize Element UI styles:
Theme Roller
The Theme Roller is an online tool that allows you to customize all the design tokens of global variables and components. You can preview your new theme in real-time and generate a complete style package based on the new theme for you to download directly. To import new style files in your project, refer to the ‘Import custom theme’ part of this section. You can also use the Theme Roller Chrome Extension to customize the theme and preview it in real-time on any website developed by Element.
Changing theme color
If you only want to change the theme color of Element, the theme preview website is recommended. The default theme color of Element is bright and friendly blue. By changing it, you can make Element more visually connected to specific projects. The above website allows you to preview the theme of a new theme color in real-time, and it can generate a complete style package based on the new theme color for you to download directly. To import new style files in your project, refer to the ‘Import custom theme’ or ‘Import component theme on demand’ part of this section.
Update SCSS variables in your project
If your project uses SCSS, you can directly change Element style variables. Create a new style file, such as element-variables.scss
, and define the style variables you want to modify. Then, import this style file in the entry file of your project instead of Element’s built CSS.
/* theme color */ $--color-primary: teal; /* icon font path, required */ $--font-path: '~element-ui/lib/theme-chalk/fonts'; @import "~element-ui/packages/theme-chalk/src/index";
Note that it’s necessary to override the icon font path to the relative path of Element’s font files.
CLI theme tool
If your project doesn’t use SCSS, you can use Element UI’s CLI theme tool to customize themes. First, install the theme generator globally or locally.
Then, install the chalk theme from npm or GitHub.If you don’t use SCSS in your project, you can customize themes with Element UI’s CLI theme tool. Here’s how to use it:
# Install globally npm i element-theme -g # Install locally npm i element-theme -D # Install the chalk theme from npm npm i element-theme-chalk -D # Install the chalk theme from GitHub npm i https://github.com/ElementUI/theme-chalk -D
After successfully installing the above packages, a command named et
is available in the CLI. Run -i
to initialize the variable file, which outputs to element-variables.scss
by default. In this file, you can find all the variables used to style Element, defined in SCSS format. Here’s a snippet:
$--color-primary: #409EFF !default; $--color-primary-light-1: mix($--color-white, $--color-primary, 10%) !default; /* 53a8ff */ $--color-primary-light-2: mix($--color-white, $--color-primary, 20%) !default; /* 66b1ff */ $--color-primary-light-3: mix($--color-white, $--color-primary, 30%) !default; /* 79bbff */ $--color-primary-light-4: mix($--color-white, $--color-primary, 40%) !default; /* 8cc5ff */ $--color-primary-light-5: mix($--color-white,
Install the CLI tool
First, install the theme generator globally or locally. We recommend local installation because when others clone your project, npm will automatically install it for them.
npm i element-theme -g
Then, install the chalk
theme from npm or GitHub:
# from npm npm i element-theme-chalk -D # from GitHub npm i https://github.com/ElementUI/theme-chalk -D
Initialize the variable file
After successfully installing the above packages, a command named et
is available in the CLI. If you installed the packages locally, use node_modules/.bin/et
instead. Run -i
to initialize the variable file, which outputs to element-variables.scss
by default. You can specify a custom output directory as well:
et -i [custom output file]
You’ll see a success message like this:
✔ Generator variables file
In element-variables.scss
, you’ll find all the variables used to style Element, defined in SCSS format.
Modify the variables
To customize the Element UI theme, you can modify the variables in element-variables.scss
. For example, to change the primary color to red, add the following code:
$--color-primary: red;
Build the theme
After saving the variable file, use et
to build your theme. You can activate watch mode by adding a -w
parameter. If you customized the variable file’s output, you need to add a -c
parameter and specify the variable file’s name. By default, the built theme file is placed inside ./theme
. You can specify a custom output directory with the -o
parameter.
et
You’ll see a success message like this:
✔ build theme font ✔ build element theme
Use the custom theme
Import the custom theme
Importing your own theme is just like importing the default theme, but this time you import the file built from “Online Theme Roller” or “CLI tool”:
import '../theme/index.css' import ElementUI from 'element-ui' import Vue from 'vue' Vue.use(ElementUI)
Import the component theme on demand
If you are using babel-plugin-component for on-demand import, just modify .babelrc
and specify styleLibraryName
to the path where your custom theme is located, relative to .babelrc
. Note that ~
is required:
{ "plugins": [ [ "component", { "libraryName": "element-ui", "styleLibraryName": "~theme" } ] ] }
If you’re unfamiliar with babel-plugin-component
, please refer to the quick start guide. For more details, check out the Element UI theme repository.
Handling UI Events with Element UI and Vue.js
When building a web application with Element UI and Vue.js, it’s essential to understand how to handle user interface (UI) events. UI events occur when a user interacts with a web page, such as clicking a button, entering text into a form, or scrolling the page. In this article, we’ll cover the basics of Element UI event handling, including how to bind Vue.js event listeners to Element UI components and common event handling scenarios.
Overview of Element UI Event Handling
Element UI components emit events in response to user actions. For example, the el-button
component emits a click
event when the user clicks on the button. You can listen for these events in your Vue.js components using the v-on
directive.
Binding Vue.js Event Listeners to Element UI Components
To bind a Vue.js event listener to an Element UI component, you use the
v-on
directive followed by the name of the event and the function to call when the event is triggered. For example, to listen for theclick
event on anel-button
component and call a method namedhandleClick
, you can use the following code:
<template> <el-button v-on:click="handleClick">Click me!</el-button> </template> <script> export default { methods: { handleClick() { console.log('Button clicked!') } } } </script>
In this example, the handleClick
method is defined in the component’s methods
object. When the click
event is triggered on the el-button
component, Vue.js calls the handleClick
method.
Examples of Common Event Handling Scenarios
1. Handling a Click Event on a Button
In this example, we will create a simple button using Element UI’s el-button
component and handle a click event to perform some action.
<template> <div> <el-button @click="handleClick">Click Me</el-button> </div> </template> <script> export default { methods: { handleClick() { console.log("Button Clicked!"); // Perform some action here }, }, }; </script>
In this example, we bind a click
event listener to the el-button
component using the @click
directive. When the button is clicked, the handleClick
method is called, which logs a message to the console and performs some action.
2. Handling a Change Event on a Checkbox
In this example, we will create a simple checkbox using Element UI’s el-checkbox
component and handle a change event to update a data property.
<template> <div> <el-checkbox v-model="checked" @change="handleChange">Check Me</el-checkbox> </div> </template> <script> export default { data() { return { checked: false, }; }, methods: { handleChange(value) { console.log("Checkbox Changed!", value); // Update some data property }, }, }; </script>
In this example, we use the v-model
directive to bind the checkbox value to the checked
data property. We also bind a change
event listener to the el-checkbox
component using the @change
directive. When the checkbox value changes, the handleChange
method is called with the new value, which logs a message to the console and updates some data property.
3. Handling a Submit Event on a Form
In this example, we will create a simple form using Element UI’s el-form
component and handle a submit event to submit the form data.
<template> <div> <el-form @submit.native.prevent="handleSubmit"> <el-form-item label="Name"> <el-input v-model="name"></el-input> </el-form-item> <el-form-item label="Email"> <el-input v-model="email"></el-input> </el-form-item> <el-form-item> <el-button type="primary" native-type="submit">Submit</el-button> </el-form-item> </el-form> </div> </template> <script> export default { data() { return { name: "", email: "", }; }, methods: { handleSubmit() { console.log("Form Submitted!"); // Submit the form data }, }, }; </script>
In this example, we bind a submit
event listener to the el-form
component using the @submit.native.prevent
directive to prevent the default form submission behavior. When the form is submitted, the handleSubmit
method is called, which logs a message to the console and submits the form data.
Best Practices and Tips for Using Element UI with Vue.js
Element UI is a powerful UI library that works seamlessly with Vue.js. Here are some best practices and tips to help you make the most out of using Element UI with Vue.js:
Performance optimization tips
- Avoid unnecessary re-renders: Use
shouldComponentUpdate
ormemo
to prevent unnecessary re-renders. For example, if a component only needs to update when a specific prop changes, you can useshouldComponentUpdate
to compare the new prop value with the previous value and only update if they are different. - Use virtual scrolling: Virtual scrolling is a technique used to render only the visible elements of a large list. This can greatly improve the performance of applications with large lists. Element UI provides a
ElScrollbar
component that can be used to implement virtual scrolling. - Minimize the use of computed properties: Computed properties are an important feature of Vue.js, but they can also have a negative impact on performance if overused. Use them sparingly and only when necessary.
- Use
v-if
instead ofv-show
for conditional rendering:v-if
removes the element from the DOM when the condition is false, whilev-show
only hides it with CSS. This can result in better performance when dealing with complex components. - Avoid unnecessary DOM manipulation: Manipulating the DOM can be expensive, especially if done frequently. Try to minimize the number of DOM manipulations your application needs by using techniques like virtual DOM.
Accessibility considerations
Accessibility considerations are crucial when developing applications to ensure they are inclusive and usable for all users, regardless of their abilities or disabilities. Here are five best practices for ensuring accessibility in your Element UI and Vue.js application:
- Use Semantic HTML: Semantic HTML helps to create a clear and meaningful structure for your application. Use HTML elements that are semantically meaningful, such as buttons for buttons, input for form inputs, and label for labeling form inputs. This makes it easier for screen readers to understand and navigate your application.
Example:
<label for="username">Username:</label> <input type="text" id="username" name="username">
- Provide Alternative Text for Images: Images should always have alternative text that describes their content. This is important for users who use screen readers. Adding an alt attribute to your image tag is a simple way to provide alternative text.
Example:
<img src="image.png" alt="A cat sitting on a window sill looking outside">
- Ensure Keyboard Accessibility: All interactive elements of your UI should be keyboard accessible. This means users should be able to navigate and interact with your application using only their keyboard. Make sure to use tab index and keyboard shortcuts appropriately.
Example:
<button tabindex="0">Click Me</button>
- Use High Contrast Colors: Use high contrast colors to ensure that all users, including those with visual impairments, can easily read and distinguish text. A contrast ratio of at least 4.5:1 between text and its background is recommended.
Example:
body { background-color: #ffffff; color: #000000; } a { color: #ff0000; }
- Provide Accessible Error Messages: Error messages should be clearly visible and describe the error in a way that is easy to understand. Use aria-describedby to associate the error message with the form input it relates to. This will allow screen readers to announce the error message when the user interacts with the form.
Example:
<label for="email">Email:</label> <input type="email" id="email" name="email" aria-describedby="email-error"> <div id="email-error" role="alert"> Please enter a valid email address. </div>
By following these best practices, you can ensure that your Element UI and Vue.js application is accessible and usable for all users.
Responsive design with Element UI
Element UI provides responsive design options for its components. To make your application responsive, follow these tips:
- Use appropriate breakpoints: Use Element UI’s breakpoints to adjust the layout of components at different screen sizes. Use
el-row
andel-col
to create a responsive grid system. - Use the
flex
attribute: Use theflex
attribute to create flexible layouts that adjust to the available space. This is especially useful for creating responsive navigation menus. - Use the
responsive
attribute: Use theresponsive
attribute to make components responsive to the screen size. For example, you can useresponsive
onel-button-group
to change the layout of the buttons at different screen sizes. - Test on different devices: Test your application on different devices to ensure that it looks and works as expected at different screen sizes.
- Use media queries: Use CSS media queries to adjust the layout of your application based on the screen size. This can be used in combination with Element UI’s responsive design options to create a fully responsive application.
Resources and Further Learning
Element UI and Vue.js are widely used web development tools with a vibrant community of developers, tutorials, and resources. Here are some useful resources to help you continue learning and using these technologies.
Official Vue.js and Element UI documentation
The official documentation for Vue.js and Element UI are great resources for getting started and learning about the different features and components available. Here are some links to the official documentation:
The documentation includes a range of examples, tutorials, and API references. It’s always a good idea to start with the official documentation when learning a new technology.
Vue.js and Element UI community resources and forums
There are several community resources and forums available for Vue.js and Element UI where you can ask questions, share ideas, and get help with any issues you’re facing. Here are some popular ones:
These communities are great places to connect with other developers and get help with any problems you may be facing. You can also browse through previous discussions and topics to learn more about common issues and solutions.
Further Learning
There are many other resources available for learning more about Vue.js and Element UI, including blogs, online courses, and video tutorials. Here are some popular ones:
These resources can help you deepen your understanding of Vue.js and Element UI, and provide you with a range of practical examples and use cases to explore.
Conclusion:
In conclusion, Vue.js and Element UI are powerful tools that can help developers create beautiful and functional user interfaces. By understanding the key concepts of Vue.js and the various components and themes available in Element UI, developers can create applications quickly and efficiently.
Recap of the article’s key takeaways:
- Vue.js is a progressive JavaScript framework that allows developers to create dynamic and reactive user interfaces.
- Element UI is a UI library built on top of Vue.js that provides a wide range of components and themes for developers to use in their applications.
- Customizing Element UI themes is easy and can be done in a number of ways, including through the online theme roller or by modifying the SCSS variables in your project.
- Handling UI events with Element UI and Vue.js is straightforward and can be accomplished through the use of event listeners and the v-on directive.
- Best practices for using Element UI include using semantic HTML, providing alternative text for images, ensuring keyboard accessibility, using high contrast colors, and providing accessible error messages.
- Resources for further learning include the official Vue.js and Element UI documentation, as well as community resources and forums.
If you are interested in learning more about Vue.js and Element UI, we encourage you to explore the resources we have mentioned in this article. Try building a simple application using Vue.js and Element UI, and experiment with customizing the theme and handling UI events. The more you practice and experiment, the more comfortable you will become with these powerful tools. Good luck!
Sure, here’s a list of terms and their definitions to help you better understand Element UI and Vue.js:
- Vue.js: A progressive JavaScript framework for building user interfaces.
- Element UI: A Vue.js component library that provides a set of customizable UI components for developers.
- Component: A modular and reusable building block for creating UI elements in Vue.js.
- Prop: A way to pass data from a parent component to a child component in Vue.js.
- Slot: A way to define placeholders for content that will be inserted into a component in Vue.js.
- Directive: A special directive in Vue.js that manipulates the behavior of the DOM.
- v-model: A directive in Vue.js that enables two-way data binding between a form input and a component data property.
- v-if: A directive in Vue.js that conditionally renders an element based on a truthy value.
- v-for: A directive in Vue.js that creates a loop to render a list of elements based on an array or object.
- Template: A component’s template is the HTML markup that defines its structure and layout.
- Script: The script section of a Vue.js component is where the component’s logic and behavior are defined.
- Style: The style section of a Vue.js component is where the component’s CSS styling is defined.
- Router: A plugin in Vue.js that enables client-side routing to create a single-page application.
- Vuex: A state management library for Vue.js that enables a centralized store for managing data in large-scale applications.
- Lifecycle hook: A method in Vue.js that is called at specific stages of a component’s lifecycle, such as created, mounted, updated, and destroyed.
- Mixin: A reusable and composable object in Vue.js that contains a set of options to merge into a component.
- Plugin: A reusable and configurable feature in Vue.js that can be installed and used across multiple components.
- Global component: A Vue.js component that can be used in any other component in the application without needing to be imported.
- Local component: A Vue.js component that is defined and used only within a specific parent component.
- Element Plus: A fork of Element UI that provides additional features, updates, and improvements.
- BEM: A CSS methodology that stands for Block, Element, Modifier and provides a structured way to name and organize CSS classes for reusable components.
- SCSS: A preprocessor scripting language that extends CSS and provides features such as variables, nesting, and mixins.
- Design Tokens: A set of named variables that represent design properties such as colors, typography, spacing, and layout.
- Theming: The process of customizing the visual appearance of an application’s UI by modifying design tokens or CSS styles.
- Accessibility: The practice of designing and developing UI components and interfaces that can be used by people with disabilities, such as visual, hearing, motor, or cognitive impairments.
- Screen reader: Assistive technology that reads aloud the content of a web page for users who are visually impaired.
- Keyboard accessibility: The practice of designing UI components that can be fully navigated and interacted with using only the keyboard, without relying on a mouse or other pointing device.
- ARIA: Accessible Rich Internet Applications, a set of attributes that can be added to HTML elements to make them more accessible for users with disabilities.
- WCAG: Web Content Accessibility Guidelines, a set of guidelines and standards for making web content more accessible to people with disabilities.