Vue3&TypeScript pit summary

Installation environment

1.node version above 12

Project creation

npm init @vitejs/app + Project name
1. Configure routing


npm install vue-router@4 --save
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
const routes: Array<RouteRecordRaw> = [
 path: "/",
 name: "Home",
 meta: {
  title: "home page",
  keepAlive: true
 component: () => import("../views/Home/index.vue"),
 path: "/login",
 name: "Login",
 meta: {
  title: "Sign in",
  keepAlive: true
 component: () => import("../views/Login/index.vue"),
const router = createRouter({
 history: createWebHashHistory(),
export default router;
2. Install VueX
npm i vuex@next --save
import { createStore } from "vuex";
export default createStore({
 state: {
 mutations: {
 actions: {
 modules: {}

Remember to mount

3. Installation internationalization
npm i vue-i18n@next -S 
npm i js-cookie -S 
npm i @types/js-cookie -D
4.vite.config.ts common configuration
npm i vite-plugin-compression
5. The module declaration declare cannot be found


declare moudle ''
6. The path module cannot be found
npm install @types/node --save-dev

Vue3.0's new grammar sugar script setup

Set esSend SEnd set td Small.. Good results. outside V Out. Come on. xx Yes. Cut. Method attribute variable parameter setting:

Options API appointment:

We need to be props Set receiving parameters inside

We need to be data Set variables inside

We need to be computed Set calculation properties inside

We need to be watch Set listening properties inside

We need to be methods Set event method inside

You'll find Options APi They all agreed on where we should do what, which forced us to split the code to a certain extent.

Now use Composition API,No longer so agreed, so the code organization is very flexible, and our control code is written in setup Just inside.

setup The function provides two parameters props and context,The important thing is to setup Not in the function this,stay vue3.0 In the interview, they become the following forms:>

We don't have any this Context, no more Options API Forced separation of code. Composition API It gives us a broader world, so we need to be more cautious and make an appointment.

For complex logic code, we should pay more attention to it Composition API Don't be stingy with your original intention Composition API To separate the code and export it into various modules.

1,**template There can be multiple nodes under the label**,Finally, you don't have to write one first DIV Yes

2,**setup Function can replace the previous data,methods,computed,watch,Mounted Other objects**,however props The statement is still outside

ref And reactive What is the difference between methods? One is to add a layer of wrapper to the value type to make it become the value of the responsive reference type. The other is that the value of the reference type becomes a responsive value. therefore**The only difference between the two is whether a layer of reference wrapper needs to be added**?The purpose is to add a responsive effect to the data.

##### Ideological advantages

**vue2 Using the idea of object-oriented programming, vue3 The idea of functional programming is adopted.**

Reason: make full use of the advantage that the combination of functional programming is greater than inheritance, and the use of functional programming is more conducive to the reuse of logical functions, webpack Packaging is more conducive to tree-shaking,It is more conducive to code compression and return value type verification, and the compressed file volume is smaller.
<script setup lang="ts">
// imported components are also directly usable in template
import Foo from "../Foo/index.vue";
import { ref } from "vue";

// write Composition API code just like in a normal setup()
// but no need to manually return everything
const count = ref(0);
const inc = () => {

    <Foo />
    HomePage assembly

JS code used in Css

Variables used in Css
.Title {
  font-size: 30px;
  @media screen and (max-width: 1000px) {
    font-size: 12px;
  color: v-bind(colorRed);
Css remove scope
:root {
  --varColor: red;
.aColor {
  color: var(--varColor);

Ref, toRef, toRefs, Reactive summary

The value copied by Ref cannot be directly calculated and must be used value

let qq = ref<number>(1);


Ref and Reactive are deep copies, which can convert general data types into responsive data types without affecting the data source.

toRef and toRefs are reference types, which convert the original data into responsive data without affecting the data source. And the UI interface will not be updated, but if there are other responsive expressions such as Reactive in the page, the UI interface will be updated at the same time.

defineProps parent-child value transfer

Define subcomponent props (data of subcomponent)


 msg: String,



const emit = defineEmits(['click']);


If I have a todoItem component, I need the item information attribute and the TodoItem interface.

1. Introduce
import { PropType } from 'vue'
2. Define interface
export interface TodoItem {
  text: string
  done: boolean

3. Attribute validation

props: {
    todo: {
      type: Object as PropType<TodoItem>,
      default: {
        text: '',
        done: false

toRefs deconstruction, Reactive

For the above code, after toRefs() changes the responsive object state into an ordinary object stateAsRefs, the extension operator of ES6 is used when return ing. Its internal properties can be used directly in the template and still have responsiveness (after using the extension operator for the responsive object state, its internal properties lose responsiveness).

After a responsive object is toRefs, it can be deconstructed to facilitate vue template use, but it will not lose its responsiveness.


ref() is a deep copy of the original data. When its value changes, it will not affect the original value; toRef() is a reference to the original data. When the value changes, it will affect the original value;

ref() receives a parameter of js basic data type; toRef() receives two parameters, the first is an object and the second is an attribute in the object;

The data created by ref() will trigger vue template update; The responsive data created by toRef() does not trigger vue template update, so the essence of toRef() is a reference and is associated with the original data


toRef is used to create a new ref for the attribute on the source responsive object, so as to maintain the responsive connection to its source object attribute.

Receive two parameters: source response object and attribute name, and return a ref data. For example, when using props data passed by the parent component, it is useful to refer to a property of props and maintain a responsive connection.


The return value is readOnly, and the property is read-only.



Value transmission mode
Multi layer component value transfer: provide inject

Values passed by parent-child components: defineProps, defineEmits

VueX status management

The difference between watch and watchEffect

1. watch is the data source that needs incoming listening, and watchEffect automatically collects the data source as a dependency.

2. watch can access the values before and after the listening state changes, but watchEffect does not.

3. watch is executed when the attribute is changed, while watchEffect is executed once by default, and then the attribute change will also be executed.

// imported components are also directly usable in template

import { ref, reactive, watch, watchEffect } from "vue";
// write Composition API code just like in a normal setup()
// but no need to manually return everything
const count = ref(0);
let a = ref<number>(0);
type obj = {
  name: string;
  age: number;
const Person = reactive<Array<obj>>([{ name: "LKK", age: 10 }]);
  () => Person[0].age,
  (newVal, oldVal) => {
    console.log(newVal, oldVal, "ssss");
watchEffect(() => {
  console.log(Person[0].age); // Even testobject If there is no change in a, it will be output again before the component is updated
const inc = () => {

const clickHandler = function () {
  Person[0].age += 1;
  // a.value++;
Monitor multiple data
  watch(() => [state.province,], ([newprovince,newcountry],[oldprovince,oldcountry]) => {
        console.log(oldprovince,'province---', newprovince);
        console.log(newcountry,'cs---', oldcountry);
        // Judge whether there is a change in the province
        if(oldprovince !== newprovince) {
        const arr = state.allCity.filter((item) => item.province == state.province);
        state.countries = arr[0].cities;
        console.log(arr); = "";
        state.detailedAdress = "";

Attribute 'name' does not exist on type 'unknown'

import type { PropType } from 'vue';

The error is reported when the user-defined component is introduced. After re running the project, it's OK??????? See wisdom bond crumbs

Method for parent element to get child element

Method 1

Child elements need to be written in defineComponent export
    <a-modal title="Title" v-model:visible="visible" :confirm-loading="confirmLoading" @ok="handleOk">
      <p>{{ modalText }}</p>
<script lang="ts">
import { ref, defineComponent } from 'vue';

export default defineComponent({
  setup() {
    const modalText = ref<string>('Content of the modal');
    const visible = ref<boolean>(false);
    const confirmLoading = ref<boolean>(false);

    const showModal = () => {
      visible.value = true;

    const handleOk = () => {
      modalText.value = 'The modal will be closed after two seconds';
      confirmLoading.value = true;
      setTimeout(() => {
        visible.value = false;
        confirmLoading.value = false;
      }, 2000);
    return {

defineComponent cannot get the background data passed by the parent component.

Method 2


// Subcomponents
<script setup>
import { defineExpose } from 'vue'
const childFun = () => {
	console.log('I am a subcomponent method')
// a key!! You need to use defineExpose to expose it here

// Parent component
	<child ref="childRef"></child>
<script setup>
import { ref } from "vue";
// Introducing sub components
import child from "./child.vue";
// Get subcomponents
const childRef = ref(null);
const fun = () => {
	childRef.value.childFun();// Method of calling subcomponent
</script >

H (tag, {attribute}, [can continue nesting h()])

In fact, both the h() function and the createVNode() function create dom nodes. Their functions are the same, but in VUE In 3, the createVNode() function has more functions than the h() function, and the performance is optimized, and the speed of rendering nodes is also faster.

import { createApp } from "vue";
//import App from "./App.vue";

import { defineComponent, h, createVNode } from "vue";
import HelloWorld from "./components/HelloWorld.vue";
const img = require('./assets/logo.png'); // eslint-disable-line
const App = defineComponent({
  render() {
        return h("div", { id: "app" }, [
            h("img", { src: img }),
            h(HelloWorld, { msg: "HelloWorld" }),
            createVNode("h1", { class: "hello" }, "HelloWorld")


Keywords: Javascript TypeScript Vue Vue.js

Added by a-mo on Mon, 07 Feb 2022 03:38:36 +0200