From the previous article Vue3 Basics and Getting Started, we learned some basic uses of Vue3, and now we’ll look at the ecology and usage tips.

How to create a project

  • VueCli4.5 +

Installation:

npm install -g @vue/cli
# OR
yarn global add @vue/cli
Copy the code

Use:

Vue create < project name >Copy the code

Alternatively, use the Vue UI command to create a vm on the GUI.

For more information on how to use VueCli, see the official documentation.

  • Vite
# npm 6.x
npm init vite@latest my-vue-app --template vue

# NPM 7+ requires additional double lines:
npm init vite@latest my-vue-app -- --template vue

# yarn
yarn create vite my-vue-app --template vue
Copy the code

For more information on how to use Vite, see the official documentation

Migration guide

As for whether the Vue2 project will be migrated to Vue3, I don’t think it is necessary, as there is no official plan to scrap OptionsApi in the future. In addition, 2.0 will also be maintained to introduce compatible composite API solutions. For new projects, consider Vue3.

If you do need to migrate, it is recommended to check the official migration guide.

Ecological state of affairs

Up to now, VUE3 has been out for a long time, the relevant ecological adaptation has been good, the basic use is completely no problem.

Here’s a rough list:

scale

vue-router4

  • Create routing
import { createRouter } from 'vue-router'
const router = createRouter({
  // ...
})
Copy the code
  • Mode configures
import { createRouter, createWebHistory } from 'vue-router'
// There are createWebHashHistory and createMemoryHistory

createRouter({
  history: createWebHistory(),
  routes: [],})/ / set the base
createRouter({
  history: createWebHistory('/base-directory/'),
  routes: [],})Copy the code
  • *Wildcard route

Instead of using path-to-regexp, the Vue Router implements its own parsing system, allows routing sorting, and implements dynamic routing.

const routes = [
  // pathMatch is the name of the argument, for example, if you jump to /not/found
  // { params: { params: { pathMatch: ['not', 'found'] }}
  // This is thanks to the last *, which means repeated arguments if you
  It is necessary that you intend to navigate directly to the path using the unmatched path name
  { path: '/:pathMatch(.*)*'.name: 'not-found'.component: NotFound },
  // If you omit the last '*', the '/' character in the argument will be encoded when parsing or jumping
  { path: '/:pathMatch(.*)'.name: 'bad-not-found'.component: NotFound },
]
Copy the code
  • <router-view>,<keep-alive><transition>
<router-view v-slot="{ Component }">
  <transition>
    <keep-alive>
      <component :is="Component" />
    </keep-alive>
  </transition>
</router-view>
Copy the code
  • Modular API
import { useRouter, useRoute } from 'vue-router'

export default {
  setup() {
    const router = useRouter() // this.$router
    const route = useRoute()  // this.$route

    function pushWithQuery(query) {
      router.push({
        name: 'search'.query: {
          ...route.query,
        },
      })
    }
  },
}
Copy the code
import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router'

export default {
  setup() {
    // Same as beforeRouteLeave, 'this' cannot be accessed
    onBeforeRouteLeave((to, from) = > {
      const answer = window.confirm(
        'Do you really want to leave? you have unsaved changes! '
      )
      // Unnavigate and stay on the same page
      if(! answer)return false
    })

    const userData = ref()

    // Same as beforeRouteLeave, 'this' cannot be accessed
    onBeforeRouteUpdate(async (to, from) = > {// Get the user only when the ID changes, such as only the query or hash value has changed
      if(to.params.id ! = =from.params.id) {
        userData.value = await fetchUser(to.params.id)
      }
    })
  },
}
Copy the code

Check out the official documentation for more uses of VueRouter4.

Vuex4

  • create
// src/store/index.js
import { createStore } from 'vuex'

export const store = createStore({
  state () {
    return {
      count: 1}}})// src/main.js
import { createApp } from 'vue'
import { store } from './store'
import App from './App.vue'

const app = createApp(App)
app.use(store)
app.mount('#app')
Copy the code
  • Modular API
import { useStore } from 'vuex'

export default {
  setup () {
    const store = useStore() // this.$store}}Copy the code

See the official documentation for more uses of Vex4.

The development tools

The scaffold

  • VueCli4.5 +
  • Vite

Development assistance

  • Volar: Volar is a language support plug-in built specifically for Vue 3. It computes everything on demand based on @vue/ ReActivity to achieve native TypeScript language service-level performance. It is highly recommended to use this plugin in your Vue3 project, and to disable Vuter, which has a lot to offer.
  • VueDevTools: this plug-in is compatible with Vue2 and vu3. You are advised to install it.

Hooks

The combined API of Vue3 allows us to use hooks when reusing code logic, so there are some handy hooks libraries in the community.

  • VueUse: VueUse is a collection of utility functions based on the Composition API
  • VueRequest: a Vue 3 Composition API for easily managing request status (SWR, polling, error retry, caching, paging, etc.

The UI component library

PC

  • Element+
  • Antdv2.0
  • NaiveUI

The mobile terminal

  • VantUI 3.0
  • NutUI 3.0

Across the side solution

  • UniApp
  • Taro

How do I package my own Hooks

Simply implement an hooks that implement the Promise:

import { reactive, toRefs } from 'vue';
export default (promiseFn, options = {}) => {
  let { autoRun = false, params = null, initData = [] } = options;
  let state = reactive({
    loading: false.data: initData,
    error: null
  });
  const run = (runParams) = > {
    state.loading = true;
    return promiseFn(runParams)
      .then((res) = > {
        state.data = res;
      })
      .catch((error) = > {
        console.error(error);
        state.error = error;
      })
      .finally(() = > {
        state.loading = false;
      });
  };
  autoRun && run(params);
  return{ run, ... toRefs(state) }; };Copy the code

Use:

let testApi = () = > configApi.list({ a: 123 }); // Interface, asynchronous task
let { loading, data, error, run } = usePromise(testApi);
run() // Call run manually, or use automatic triggering
Copy the code

Personal use template

This template may not be beautiful or suitable for you, there are many excellent templates on the Internet, but I do not want to make this one too complicated, many online are very perfect functions, but the attendant is the use of cost, so I only package some very basic things, reduce the difficulty of getting started. This UI is just for my project (you know the aesthetic of some products), if you feel ugly, it is easy to redesign, or use other excellent templates.

Access to

  • GitHub
  • MisthinTools: MisthinTools is a development aid software that currently provides project templates and automatic deployment. You can also download this template.

Functions overview

  • Data request encapsulation
  • The Mock data
  • Page and button authentication
  • Commonly used layout
  • Some common tools