Please indicate the source for reprinting: Grape City official website, Grape City provides developers with professional development tools, solutions and services, and empowers developers.
Today, what we bring to you is an open source project based on vue3: New Energy Vehicle Battery Range Calculator. This is a workshop. By completing the project, we can intuitively feel the power of vue3 and understand some of the best practices of the project.
The background of the project is a new energy vehicle that has attracted much attention. After nearly 6 years of development, new energy vehicles have been widely popularized in the market, from a "big toy" to the cornerstone of future transportation. The project takes the most concerned battery life in the new energy vehicle industry as an example, and uses vue3 technology to build a battery range calculator to show the development method and experience of using Vue.js to make dashboards.
Environmental preparation
Before starting to read this tutorial, we need to make the following preparations to set up the project environment:
- Install stable Node.js version 8.9 or higher (https:// nodejs.org/en/download/)
- Install Yarn ( https://yarnpkg.com)
- Clone this Github repository https://github.com/petereijgermans11/workshop-reactjs-vuejs
After the environment is ready, we can read README.md to get an overview of the project.
Unlike common development projects, the most interesting part of this project is that it is not a final application, but a flawed application, the workshop. We need to repair it and further develop it, and master the vue development skills in the process.
Before officially starting work, let us first understand the structure of this project.
Project structure introduction
workshop-reactjs-vuejs/vuejs-app/src is the source directory of the workshop, and the structure is shown in the figure below. main.js is the entry point of the application, and App.vue is the input component of the application.
(Project source code structure)
Project entrance
Compared with vue2, the way of creating Vue3 applications has been changed. You need to import the new createApp() method instead of using new Vue(), and then call this method to pass the App.vue component (entry component).
Then we will call the mount method on createApp and pass a CSS selector to identify the mount element. This process is the same as the $mount example method in Vue 2.
(Project entrance)
Detailed explanation of App.vue components
(app.vue组件)
App.vue is the entry component of the application and consists of the following parts.
1. Script
In the above figure, the name property represents the name of the component (the name is "app"). The subcomponents used by this component are defined in components-property. Here, TeslaBattery is a subcomponent of the App.vue component, which will be introduced later. To use the TeslaBattery component, you must first import it (import Tesla-Battery from "...")
In the data()-function, we can define and initialize state variables, such as imported logo and greeting attributes. To render the logo and greeting, they must be defined in the template. Finally, the entire component must be exported (via export default {}) so that it can be imported into other components and main.js again.
2. Template
The template is responsible for defining the output generated by the component. Vue.js uses HTML-based template syntax to enable data ()-function to be bound and easily presented. The simplest form of data binding is text interpolation using Mustache syntax (double brackets): {{greeting}}
In the above example, {{greeting}} replaces Hello Tesla !!! as a value related to data()-function. At the top of this greeting, use img-tag to present the logo. To assign the logo to the img src-attribute, use the attribute to bind it. Attribute binding is often used in this application, you can use: v-bind <img :src="logo"<img v-bind:src="logo"> to bind
Finally, use the <tesla battery>-tag to instantiate and render the TeslaBattery component. Kebab case must be used for this label, this part will be discussed in detail later
3. Style
In Vue, we use SCSS files to style the entire application, so I won’t introduce it here.
Container vs Presentation component
After introducing the basic project architecture, let's see how the UI part of the project works. The application contains an entry application component, which contains a sub-component TeslaBattery. The TeslaBattery sub-component includes the following secondary sub-components:
-TeslaCar: Use wheel animation to render TeslaCar images.
-TeslaStats: The maximum battery range used to render each Tesla model. The following models are involved: 60, 60D, 75, 75D, 90D and P100D.
-TeslaCounter: Manually control speed and external temperature.
- TeslaClimate: When the outside temperature exceeds 20 degrees, change the heating to air conditioning.
- TeslaWheels: Manually adjust the wheel size from 19 inches to 20 inches.
These components ultimately constitute the dashboard that the user sees.
(Finally displayed dashboard)
The following code block clearly shows the hierarchical relationship of the components, and both the Container component and the Presentation component are used in the project. "Tesla battery components" are container components. The basic subcomponent is the Presentation component. In this way, components can be divided into two categories, which is conducive to our repeated use in the development process.
(Component level)
The characteristics of the two components are compared as follows:
Container component
-Can contain both presentation and container components.
-Create data through "props" and transfer the data to subcomponents.
-Execute logic based on incoming events.
-Carry out state management and know the time for component rendering.
-Has state attributes and tends to act as a data source.
Presentation component
-The presentation component is also called "dumb component", and the user interface is its key part.
-TeslaCar is a dummy component that ensures the rendering of TeslaCar images.
-Receive data through "props" and return the data to the parent component through events.
-Usually there is no state and does not depend on the rest of the application.
(Component tree)
This division method has the following advantages and is worth recommending.
-High reusability
-Dumb components are easier to test: only receive "props", emit events and return part of the UI
-High readability: less code and clear organization, easy to understand and adjust
-Provide consistent content and prevent code duplication
Pass data to sub-components through Props
As can be seen in the figure below, we use props to pass stats-data (from the stats() function) from the TeslaBattery component to the TeslaStats component, linking the upper and lower components.
(Use props to pass data)
For specific operations, you need to use the v-bind or colon operator in the TeslaBattery component template.
(Pass stats data)
This component contains a props-property in the script part for receiving stats-data. The data type of this attribute is an array. In this example, we use the v-for command from Vue.js to traverse the statistics and display them in a specific order.
We can define custom filters in filters-property. For example, the filter "lowercase" can display the model name in lowercase. In the project, we customized a filter to convert miles to kilometers.
Composition API instead of filters-property
In Vue 3, we can no longer use filters-property. In order to develop a filter that "converts miles to kilometers", we need to use the Compostion API. Compostion API is a function-based API, usually used to combine and reuse the logic of each component.
First, we need to create a JavaScript file composable.js to export the data and methods we need to use, such as the filter "Convert miles to kilometers".
(Code for encapsulation filter)
Then, we import composable.js into the components that need to use the filter, and then these filters can be used in it.
(Import and enable filter code)
Use v-model to achieve two-way data binding
In Vue3, we can use the v-model instruction in the template of each component to achieve two-way data binding.
In this project, the TeslaCounter component needs to bind speed to the TeslaBattery component.
(Two-way data binding between components)
We use the v-model command in the TeslaBattery component template to bind the speed attribute (vehicle speed) to the TeslaCounter component.
(Code to pass data using v-model)
As a receiving component, TeslaCounter needs to accept the modelValue property in props. In addition, the @update:modelValue event needs to be emitted to notify data changes. The emit operation is triggered in the increment() method. When the speed changes, the latest data is "pushed" to the TeslaBattery component to which it is bound.
(Code for emit event notification)
to sum up
The above is the core introduction of the source code in the open source project new energy vehicle battery range calculator. There are more excellent practices in the project that are worthy of your study and reference.
In addition, a PPT file was added to the project, detailing practices such as two-way data binding through v-model instructions, using buttons to assign events to events, and creating other components.
In the future, we will recommend more interesting open source projects for everyone to learn about the development and actual combat of front-end technologies such as vue.
Reading expansion:
If you're already familiar usage Vue3, you want to understand the project Vue3 other instances, where you can read this article , learn more about Vuede new scaffolding tools: Vite. Vite is a web development and build tool driven by native ESM. Developed based on the browser's native ES imports in the development environment, and packaged based on Rollup in the production environment.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。