I have always thought that the framework is just a tool, and there is no need to learn if you don’t use it at work. When you need to use it, you can learn it.

Therefore, I have only a superficial impression of the very popular Vue framework in China:

  • Vue is a progressive JavaScript framework
  • Vue2 implements responsiveness by intercepting objects with defineProperty, while Vue3 implements responsiveness by Proxy
  • Vue3 adds the Composite API to address code reuse and maintainability issues

In order to expand the DevUI ecosystem and make DevUI best practices available to more developers, we officially launched the Vue DevUI open source project in The community in March this year, attracting many community friends to join us.

At present, 35+ component owners have claimed 60+ components 👏🎉🥳

The following is a roster of contributors:

Gitee.com/devui/vue-d…

I also took advantage of this opportunity to systematically study Vue3 and summarize the key features of Vue3 from a beginner’s point of view (just from my own point of view, not necessarily from the documents).

This paper is described from the perspective of the following technology stack:

💡 Tip: As of August 7, 2021, the versions of the above libraries/frameworks are the latest.

Start running

The fastest way for a young person to learn a new skill is:

Start running

After running, we’ll get a feel for the new technology, and the documentation will be clearer later.

Another is to think more, with problems to learn, memory will be more profound, and it is easier to understand the principle.

In the future, I will add links to the official website for the new knowledge we learn in the process of learning. However, these official website materials are only a reference for further study. The key is that we should think about ourselves and learn with questions.

Vite is a recommended tool for Vue3 development, it is said to be very silky, so the first step is to build a Vite project to run up.

Go straight to the start section of the website and you’re done with one command:

yarn create vite learning-vue3 --template vue-ts
Copy the code

The –template parameter is used to select a project template. In our case, it is vue-ts: vue 3 + Typescript + Vite

In addition to creating Vue projects, Vite can also commonly React/Preact/Svelte and other framework projects.

Sure enough, Vite was fast, creating a basic scaffolding project in less than 3s.

$yarn create vite learning-vue3 -- Template Vue-ts yarn create v1.22.10 [1/4] 🔍 Resolving Packages... (2/4) 🚚 Fetching packages... [three] 🔗 Linking dependencies... [4/4] 🔨 Building fresh Packages... Success Installed "[email protected]" with binaries: - create-vite - cva [# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ####################################################################################] 232/232 Scaffolding project in /devui/kagol/learning-vue3... Done. Now run: CD learning-vue3 yarn yarn dev ✨ Done in 2.69s.Copy the code

And very nicely suggested the next command to execute:

Done. Now run:

  cd learning-vue3
  yarn
  yarn dev
Copy the code

Follow the prompts and we’ll soon have the project running!

First impressions of Vue components

Splash screen the bottom, there is a guide, let’s edit the components/HelloWorld. Vue this file, test the hot update (HMR) function.

Let’s find this file helloWorld.vue, and let’s take a look at its structure.

This file has a.vue file suffix, which means it is a VUE component.

A Vue component consists of three parts:

  • One at the top<template>The label
  • There’s one in the middle<script lang="ts">The label
  • Here’s one at the bottom<style scoped>The label

This is the same structure we used when we first learned how to write HTML pages on the front end, splitting HTML/CSS/JavaScript into three blocks.

But we did notice one difference:

  • The HTML part is used<template>Wrapped with this special label;
  • <script>There’s one more partlang="ts"Property that stands for supportTypeScript;
  • <style>There’s one more partscopedProperty, which represents local styles, that is, styles written here are specific to the current Vue component.

These are the basic characteristics of the Vue component as observed so far.

< the template > analysis

We’ll notice that there are some HTML elements inside, which seem to be the same as writing HTML, but if you look closely, there are some differences:

  • The first is the part wrapped in double braces in line 2{{ msg }}This is a little different from the HTML we’ve written before, this is a Vue template syntax calledText interpolationThe MSG inside is the component variable, and the value of the variable is rendered to the outer layer<h1>Inside the label.
<h1>{{ msg }}</h1>
Copy the code
  • Line 30 is one<button>The tag, we’re familiar with it as a button, there’s also a button insideText interpolationIs bound to something calledcountComponent variable, and one more@clickWe haven’t seen this before. This is VueeventTo bind a button’s click event.
<button type="button" @click="count++">count is: {{ count }}</button>
Copy the code

Vite hot update – template

Let’s try modifying the contents of the template. For example, the last line of the template should read:

hot module replacement.
Copy the code

to

hot module replacement(HMR).
Copy the code

Let’s see what happens to the page.

As can be seen from the above GIF, once the template content is modified and the file is saved, the page content is refreshed immediately, with almost no delay and no page refresh. The development experience is very smooth.

< script > analysis

Now that we have an overview of the templates section, let’s look at the scripts section.

Import the Vue method

The first line of the script imports two methods from Vue:

  • Ref: returns a responsive and variable ref object;
  • DefineComponent: Used to define a synchronous Vue component.
import { ref, defineComponent } from 'vue'
Copy the code

These two methods are high-frequency and must be kept in mind.

Export the Vue component

Line 39 exports a Vue component.

export default defineComponent({
  name: 'HelloWorld'.props: {
    msg: {
      type: String.required: true}},setup: () = > {
    const count = ref(0)
    return { count }
  }
})
Copy the code

The Vue component is defined through the defineComponent method, which takes an object with three properties:

  • Name: a string representing the name of the component;
  • Props: an object that represents the input parameter of a component. This is the portal through which the component interacts with the outside world. When the outside uses the component, data can be passed inside the component using props.
  • Setup: An arrow function. This is the entry point to Vue3’s new Composite API. This function is executed before the component is created and after the props are resolved.

Components into the reference

Line 42 defines a variable called MSG, which we’ve seen before in the template, but what is its value?

  props: {
    msg: {
      type: String,
      required: true
    }
  },
Copy the code

We note that MSG is nested inside the props. This means that it is an incoming parameter to the component, the API that the component uses to interact with the outside world, so its value should be passed in from the outside.

Where did it come from? A component is used by its name, so we searched the source code for the name of the component: HelloWorld, and found that it is used in app.vue:

<HelloWorld msg="Hello Vue 3 + TypeScript + Vite" />
Copy the code

Use the Vue component

Using a component is almost the same as using a normal HTML tag (such as div), except that you need to import and declare the component before you can use it.

The way to use a component is simple in three steps:

  • Imported components
  • Announcement component
  • Using the component

Vite hot update -script

Let’s change the value of MSG to Hello everyone! I’m learning Vue 3 + TypeScript + Vite) and see what happens to the page.

From the above GIF, we can see that the effect is the same as modifying the template. After changing the value of MSG, the page content will be refreshed immediately after saving the file.

Hello Vue 3 + TypeScript + Vite
Copy the code

It immediately became:

Hello everyone! I'm learning Vue 3 + TypeScript + Vite
Copy the code

There were almost no delays, pages didn’t refresh, and the development experience was silky.

The ref object of the response

Line 48 defines a count variable:

  setup: () => {
    const count = ref(0)
    return { count }
  }
Copy the code

We’ve seen this variable before in the template, and its value is the count defined here, and we notice that the value of count is returned by a call to a function called ref, and the parameter to that function is the number 0. Why wrap a layer of ref, instead of just assigning 0 to the count variable?

const count = 0
Copy the code

Wouldn’t it be simpler to just assign?

Let’s first look at the introduction of ref on the official website:

Accepts an internal value and returns a responsive and variable REF object. The ref object has a single property '.value 'pointing to an internal value.Copy the code

To understand what the ref function does, try clicking on the count is: 0 button inside the page.

Click on the discovery inside the value immediately becomes:

count is: 1
Copy the code

At this point we will:

const count = ref(0)
Copy the code

Modified to:

const count = 0
Copy the code

Click the Button button again and see that the value has not changed.

The ref function returns a responsive ref object:

Reactive means that the value of the variable is dynamic. Some action (clicking a button) changes its value. The text interpolation in the template immediately changes, and the page content refreshes.

If no count is wrapped by the ref function, then it is not reactive, and the contents of the template do not change after the button changes its value.

One caveat:

Variables defined in setup must be returned before they can be used in the template, or the interpolation will not be rendered and will be alerted in the browser console

[Vue warn]: Property "count" was accessed during render but is not defined on instance.
Copy the code

TypeScript support

The lang=”ts” property in

First define a type:

type Size = 'sm' | 'md' | 'lg'
Copy the code

Then define a variable in the setup method to use this type:

const size = ref<Size>('md')

return { size } // Remember to return
Copy the code

Finally, use this variable in the template via text interpolation:

<p>{{ size }}</p>
Copy the code

Because we added lang=”ts” to

Delete “ts” from “lang”, save the file and refresh the page. The page is white and the browser console has an error:

Uncaught SyntaxError: unexpected token: identifier
Copy the code

The Size type defined earlier also appears with a red wavy underline.

The type declaration must be used in TypeScript files:

Type aliases can only be used in TypeScript files.
Copy the code

TypeScript type errors are highlighted

This doesn’t seem to show the benefits of TypeScript, so let’s take a look at the benefits of TypeScript in this demo.

We add an addSize method to increase the size:

const addSize = () = > {
  size.value = 'lg' // It is ok to assign the size variable to the value defined in type size
}

return { addSize } // Remember to return
Copy the code

Use this method in the template:

<button type="button" @click="addSize">Add size</button>
Copy the code

If you assign a complex value of size to a value defined by the size type, such as large, the Vetur type check immediately prompts and the corresponding assignment code is underlined with red wavy lines:

At this point we can immediately alert:

The code here might not be right

💡 Tip: Vetur is a VSCode plugin that does syntax highlighting and TypeScript type checking for.vue files.

summary

The

  1. The defineComponent method is used to define the Vue component
  2. The name of a Vue component is defined by the name attribute, which uniquely identifies a component
  3. The Vue component uses the props property to interact with the outside world
  4. The Setup method is the entry point to the Vue3 Composite API
  5. Using Vue components is similar to using HTML elements, except that you need to import and declare components before you can use them
  6. Ref is used to return a responsive object
  7. lang="ts"To support TypeScript

The < style > analysis

Finally, look at the

<style scoped> a { color: #42b983; } label {margin: 0 0.5em; font-weight: bold; } code { background-color: #eee; padding: 2px 4px; border-radius: 4px; color: #304455; } </style>Copy the code

The scoped property is added to the

Layout Component Styles

To understand what local styles mean, let’s write a tag in the other component and see if it has the same style as in the HelloWorld component. In the HelloWorld component, the code tag looks like this (with a gray background color) :

code {
  background-color: #eee;
  padding: 2px 4px;
  border-radius: 4px;
  color: #304455;
}
Copy the code

We’ll also write a code tag in app.vue:

<code>Vue DevUI</code>
Copy the code

We find that what we write in the Style of the HelloWorld component does not affect the code in the App component. This is the local style.

Comparing the HTML elements of the two, we find that the elements in the HelloWorld component have a special attribute that starts with data-v-, and the corresponding CSS rule has this selector.

This is very similar to the Angular encapsulation property.

Vite hot update – style

In addition to template and Script hot updates, Vite also supports style hot updates, which are just as silky.

summary

In this article, we started an initial project with Vite and got a first look at the Vue component. Let’s consolidate with a brief summary.

  • First, I built a Vue3+TypeScript+Vite project
  • Then I looked at the overall structure of the Vue component (.vueTemplate +script+style)
  • The Template, Script, and style blocks are then analyzed separately
  • Template is very similar to HTML, with some Vue specific additionsTemplate syntax, such asText interpolation, event binding, etc
  • Script is where the component logic is definedlang="ts"Support the TypeScript
  • defineComponentandrefDefineComponent is used to define the Vue component and ref is used to generate a responsive REF object
  • The argument to the defineComponent method is an object in whichnameProperty is used to define the name of the Vue component, which is referenced by name when the component is used
  • Using Vue components is similar to using HTML tags, except that you import and declare the components first
  • propsProperties are used to define the API for the component to interact with the outside world and are key to component design
  • setupMethod is Vue3Composite APIWhich is executed before the component is generated and after the props are resolved
  • Style is used to write the style of the componentscopedSupports local styles that are only valid for the current component

Vue DevUI is under development at 🔥. Welcome to join us and build a Vue open source component library based on DevUI design concept.

We have the following advantages over other component libraries in the community:

  1. Vue DevUI was designed and developed based on the DevUI design values of immersion, simplicity, and flexibility, which have been tested by many of DevCloud’s commercial projects to ensure quality and experience
  2. Vue Devui is positioned as a cross-end component library to ensure that it meets the needs of PC /mobile multi-end users
  3. Devui is a team focused on user experience, with 50+ excellent designers and engineers behind it, ensuring excellent product experience and advanced technology
  4. We have several featured components such as Gantt charts, category search, Sprite navigation, and an icon component that supports both custom font ICONS and custom SVG
  5. We support the standard features of component libraries such as load on demand, custom themes, and internationalization.

Here is the source code for the project:

Gitee.com/devui/vue-d…

Participate in the contribution can be added to the small assistant wechat: Devui-official, pull you into the Vue Devui core members group ~ 😋😋

Welcome to our DevUI component library and light up our little star 🌟 :

Github.com/devcloudfe/…

Also welcome to use DevUI newly released DevUI Admin system, out of the box, 10 minutes to build a beautiful atmosphere of the background management system!

Once again: DevUI 12 and DevUI Admin 2.0 are coming!

DevUI 12 will be released on The 10th of this month, and there are so many interesting new features in addition to updating Angular 12. Look forward to it!

DevUI Admin 2.0 will also be released on The 17th of this month, providing a magical piece of dark technology, let’s wait and see!

Reference:

Vue3 Chinese documents