Teach you 5 knowledge points to make Vue3 development smoother
This article brings you knowledge about development in Vue, and compiles 5 little knowledge that can improve development efficiency, making your Vue3 project development smoother and smoother. I hope it will be helpful to everyone.
1. Setup name enhancement
Vue3’s setup syntax sugar is a good thing, but the first problem caused by using setup syntax is that it cannot be customized. name, and when we use keep-alive, we often need name. This problem is usually solved by writing two script tags, one using setup and one not using it, but this is definitely not elegant enough.
<script> import { defineComponent, onMounted } from 'vue' export default defineComponent({ name: 'OrderList' }) </script> <script setup> onMounted(() => { console.log('mounted===') }) </script>
At this time, with the help of the plug-in vite-plugin-vue-setup-extend, we can solve this problem more elegantly. Instead of writing two script tags, we can directly define the name on the script tag.
Installation
npm i vite-plugin-vue-setup-extend -D
Configuration
// vite.config.ts import { defineConfig } from 'vite' import VueSetupExtend from 'vite-plugin-vue-setup-extend' export default defineConfig({ plugins: [ VueSetupExtend() ] })
Use
<script setup name="OrderList"> import { onMounted } from 'vue' onMounted(() => { console.log('mounted===') }) </script>
2. API automatic import
setup syntax allows us to use the variables and methods on the template without returning them one by one, which greatly frees up our hands. However, for some commonly used VueAPIs, such as ref, computed, watch, etc., we still need to manually import them on the page every time.
We can realize automatic import through unplugin-auto-import, and you can use Vue's API in the file without importing.
Installation
npm i unplugin-auto-import -D
Configuration
// vite.config.ts import { defineConfig } from 'vite' import AutoImport from 'unplugin-auto-import/vite' export default defineConfig({ plugins: [ AutoImport({ // 可以自定义文件生成的位置,默认是根目录下,使用ts的建议放src目录下 dts: 'src/auto-imports.d.ts', imports: ['vue'] }) ] })
The auto-imports.d.ts file will be automatically generated after installation and configuration.
// auto-imports.d.ts // Generated by 'unplugin-auto-import' // We suggest you to commit this file into source control declare global { const computed: typeof import('vue')['computed'] const createApp: typeof import('vue')['createApp'] const customRef: typeof import('vue')['customRef'] const defineAsyncComponent: typeof import('vue')['defineAsyncComponent'] const defineComponent: typeof import('vue')['defineComponent'] const effectScope: typeof import('vue')['effectScope'] const EffectScope: typeof import('vue')['EffectScope'] const getCurrentInstance: typeof import('vue')['getCurrentInstance'] const getCurrentScope: typeof import('vue')['getCurrentScope'] const h: typeof import('vue')['h'] const inject: typeof import('vue')['inject'] const isReadonly: typeof import('vue')['isReadonly'] const isRef: typeof import('vue')['isRef'] // ... } export {}
Use
<script setup name="OrderList"> // 不用import,直接使用ref const count = ref(0) onMounted(() => { console.log('mounted===') }) </script>
Above we only imported vue in the configuration of vite.config.ts, imports: ['vue'], in addition to vue, you also You can import other ones such as vue-router, vue-use, etc. according to the documentation.
Personally, it is recommended to only automatically import some familiar APIs. For example, we are familiar with the vue API during development and can write it with our eyes closed. For some unfamiliar libraries like VueUse, It is better to use import. After all, the editor has prompts and it is not easy to make mistakes.
Solution to eslint error reporting problem
Using it without import will cause eslint to prompt an error reporting. This can be solved by installing the plug-in **vue-global-api** in eslintrc.js.
// 安装依赖 npm i vue-global-api -D // eslintrc.js module.exports = { extends: [ 'vue-global-api' ] }
3. Farewell to .value
As we all know, ref requires us to add .value when accessing variables, which makes many developers feel uncomfortable.
let count = ref(1) const addCount = () => { count.value += 1 }
This is especially true later. A new syntactic sugar proposal for ref was also submitted.
ref: count = 1 const addCount = () => { count += 1 }
This proposal caused a lot of discussion in the community as soon as it came out. It has been a long time, so I will no longer talk nonsense about this topic here.
What I introduce here is another way of writing, which is also an official solution later. Add $ before ref. This function is turned off by default and needs to be turned on manually.
// vite.config.ts import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [ vue({ refTransform: true // 开启ref转换 }) ] })
After turning it on, you can write like this:
let count = $ref(1) const addCount = () => { count++ }
The configuration of this syntax sugar is slightly different according to different versions. Here is the version of the relevant plug-in I use:
"vue": "^3.2.2", "@vitejs/plugin-vue": "^1.9.0", "@vue/compiler-sfc": "^3.2.5", "vite": "^2.6.13"
4. Automatically import images
In Vue2 we often quote images like this:
<img :src="require('@/assets/image/logo.png')" />
But require is not supported in Vite, and the quoted images become the following:
<template> <img :src="Logo" /> </template> <script setup> import Logo from '@/assets/image/logo.png' </script>
Every time you use an image, you have to import it, which obviously delays everyone's time to fish. At this time, we can use vite-plugin-vue-images to automatically import images.
It feels great, but variable conflicts are easy to occur, so use with caution!
Installation
npm i vite-plugin-vue-images -D
Configuration
// vite.config.ts import { defineConfig } from 'vite' import ViteImages from 'vite-plugin-vue-images' export default defineConfig({ plugins: [ ViteImages({ dirs: ['src/assets/image'] // 指明图片存放目录 }) ] })
Use
<template> <!-- 直接使用 --> <img :src="Logo" /> </template> <script setup> // import Logo from '@/assets/image/logo.png' </script>
5. Ignore the .vue suffix
I believe many people ignore the .vue suffix when importing files when developing Vue2. But in Vite, ignoring the .vue suffix will cause an error.
import Home from '@/views/home' // error import Home from '@/views/home.vue' // ok
According to You Dada’s answer, the requirement to write suffixes is actually deliberately designed this way, that is, everyone is encouraged to write like this.
But if you really don’t want to write, the official support is provided.
// vite.config.ts import { defineConfig } from 'vite' export default defineConfig({ resolve: { extensions: ['.js', '.ts', '.jsx', '.tsx', '.json', '.vue'] } })
It should be noted here that when configuring extensions manually, remember to add the suffix of other types of files, because other types of files such as js can ignore the suffix import by default. If you do not write it, the import of other types of files will be ignored. It becomes necessary to add a suffix.
Although this can be done, the official document says that it is not recommended to ignore the .vue suffix, so it is recommended that you still write .vue honestly in actual development.
[Related recommendations: "vue.js Tutorial"]
The above is the detailed content of Teach you 5 knowledge points to make Vue3 development smoother. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values for each element; and the .map method can convert array elements into new arrays.

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.
