1, Vite
Uvu introduced vite’s tools during the Vue 3.0 beta live broadcast, emphasizing that the unpackaged development server for Vue single-page components can run requested Vue files directly in the browser
Very novel, this blog uses it to build a VUE3 project try
Vite is a Web development and construction tool based on ESModule, a native module system for modern browsers. Package based on Rollup in production environment
- Quick cold start of the server
- Instant Hot Module Replacement (HMR)
- True on-demand compilation
Node version requirements: Node >= 10.16.0
2. Project construction
To build a project with Vite, vite+ TS +vue3 requires only one command
npm init @vitejs/app <project-name> --template vue-ts
Copy the code
Install related plug-ins
Vue routing
npm install vue-router@4 --save
Copy the code
Vue3 state manager
npm i vuex@next --save
Copy the code
Vant3 component UI library
npm i vant@next -S
Copy the code
Network request AXIOS plug-in
npm i -s axios
Copy the code
3, configure vite.config.ts (default project root directory)
Vite.config. ts is equivalent to vue.config.js in the @vue-cli project
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import vitePluginImp from 'vite-plugin-imp' import path from 'path'; @types/node import styleImport from "vite-plugin-style-import"; Import viteCompression from "vite-plugin-compression"; //gzip plugin const resolve = (dir: string) => path.join(__dirname, dir); / / https://vitejs.dev/config/ export default defineConfig ({base: ". / ", / / package path server: {open: True,// Whether to automatically open the browser (default false) port:3000,// enable port proxy: {// option written '/ API ': 'http://123.56.85.24:5000' / / proxy}, cors: true / / open the cross-domain}, resolve: {alias: {' @ ': Path.resolve (__dirname, './ SRC ')// Set alias}}, // Style related rules CSS: {preprocessorOptions: {CSS: {// Load global style additionalData: `@use './src/assets/css/reset.css'; `,} / / SCSS: {/ / / / global style/loading/additionalData: ` @ use '. / SRC/assets/styles/var. SCSS '; // @use './src/assets/styles/common.scss'; `, // }, }, }, plugins: [ vue(), viteCompression({ verbose: true, disable: false, threshold: 10240, algorithm: "gzip", ext: ".gz", }), vitePluginImp({ libList: [ { libName: 'vant', style(name) { if (/CompWithoutStyleFile/i.test(name)) { // This will not import any style file return false } return 'vant/es/${name}/index.css'}},]})], // Package related rules build: {target: "es2020", // specify es version, browser compatibility outDir: "Dist ", // specify output path assetsDir: "assets", // specify static resource path cssCodeSplit: true, // CSS code split, disable all styles in one CSS sourcemap: TerserOptions: {// Remove console compress: {drop_console: true, drop_debugger: true, }, }, }, })Copy the code
4. Configure Router routes (Different from vue2 routes, routes need to be manually created and compiled in Vue3+Vite projects)
Create a router folder under SRC and create index.ts in the router folder
import { createRouter, createWebHistory } from 'vue-router' const routes = [ { path: '/', name: 'Home', component: () => import('/@/views/Home.vue') }, { path: '/lifeCycle', name: 'lifeCycle', component: () => import('/@/views/LifeCycle. Vue ')}] // createWebHistory // createWebHashHistory Export default createRouter({history: createWebHistory(), routes})Copy the code
5, TS types configuration
Create tsconfig.json in the project root directory and write the relevant configuration
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"lib": ["esnext", "dom", "dom.iterable", "scripthost"],
"types": [
"node"
]
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
"exclude": [
"node_modules"
]
}
Copy the code
Create a folder in the SRC directory and configure the TS type in the folder
-
shims-vue.d.ts
declare module '*.vue' { import { ComponentOptions} from "vue" const componentOptions: ComponentOptions export default componentOptions } Copy the code
-
images.d.ts
declare module '*.svg' declare module '*.png' declare module '*.jpg' declare module '*.jpeg' declare module '*.gif' declare module '*.bmp' declare module '*.tiff' Copy the code
-
main.ts
import { createApp } from 'vue' import App from './App.vue' import router from './router'; createApp(App) .use(router) .mount('#app') Copy the code
Now that the configuration and environment are complete, you can start writing bugs 🤣
6. Vue3 related knowledge points
-
setup
Vue3 integrates all apis with the setup function; It is executed only once, before the lifecycle function, so the current instance this is not available in the setup function and cannot be used to call the method defined in the vue2 notation
It will take two arguments: props, context
Context setup(props, context) {return {// Data and methods to bind}}Copy the code
-
props
The props in the setup function is reactive, and when a new prop is passed in, it will be updated. However, because the props are reactive, it cannot be deconstructed using ES6 because it eliminates the responsiveness of the prop
If you need to deconstruct a prop, you can do so safely by using toRefs in the Setup function
import { toRefs } from 'vue' setup(props) { const { title } = toRefs(props) console.log(title.value) } Copy the code
-
context
Context exposes three component properties: {attrs, slots, emit} It is a normal JavaScript object, not reactive, which means you can safely use ES6 deconstruction of context
-
Life cycle function
Access a component’s lifecycle hook by prefixing the lifecycle hook with “on”
Because setup runs around the beforeCreate and Created lifecycle hooks, they do not need to be explicitly defined in other words, any code written in these two hooks should be written directly in the Setup function
The setup () {onMounted (() = > {the console. The log (' mount components')}) onUnmounted (() = > {the console. The log (' component uninstall ')}) onUpdated (() = > { Console. log(' component update ')}) onBeforeUpdate(() => {console.log(' component will update ')}) onActivated(() => {console.log('keepAlive component ') Activate ')}) onDeactivated(() => {console.log('keepAlive component not activated ')}) return {}}Copy the code
-
Ref, reactive
Ref: It is possible to wrap a common value as responsive data, but only simple values. Internally, it is possible to wrap a value as an object, and then handle the value wrapped by ref through defineProperty. Instead of this.$refs
Reactive: Reactive processing of complex data. Its return value is a proxy object. When the setup function returns a proxy object, toRefs can be used to structure the proxy object for use in the template
<template> <div> <div> <ul v-for="ele in eleList" :key="ele.id"> <li>{{ ele.name }}</li> </ul> <button @ click = "addEle" > add < / button > < / div > < div > < ul v - for = "ele in todoList:" key = "ele. Id" > < li > {{ele. Name}} < / li > < / ul > < button@click ="addTodo"> add </ button@click ="addTodo"> </ button@click ="addTodo"> </ button@click ="addTodo"> </ button@click ="addTodo"> </ button@click ="addTodo"> toRefs } from 'vue' export default { setup() { // ref const eleList = ref([]) function addEle() { let len = eleList.value.length eleList.value.push({ id: len, name: } // reactive const dataObj = reactive({todoList: [] }) function addTodo() { let len = dataObj.todoList.length dataObj.todoList.push({ id: len, name: 'Reactive' + len})} return {eleList, addEle, addTodo... toRefs(dataObj) } } } </script>Copy the code
-
Computed, watch
// computed let sum = computed(() => dataObj.todoList.length + eleList.value.length) Console. log('setup references computed to. Value: '+ sum.value) // watch watch(eleList,(curVal, oldVal) => {console.log(' listener: ', curVal, oldVal) }, { deep: true } )Copy the code
-
watchEffect
Reactive data referenced in a function is tracked responsively, and the function is re-executed when the reactive data changes
Const stop = watchEffect(() => console.log(count.value)) // Stop listening stop()Copy the code
You can also stop listening. WatchEffect returns a function that stops listening after execution
Same as VUe2:
const unwatch = this.$watch('say', curVal => {}) Copy the code
// Stop listening unwatch()Copy the code
-
UseRoute, useRouter
import {useRoute, UseRouter} from 'vue-router' const route = useRoute(); $route const router = useRoute() The enclosing $routerCopy the code
Route Is used to obtain the current route data. Router is used to redirect routes
-
vuex
Configuration:
Create the store folder in the SRC directory and create the index.ts file
import { createStore } from "vuex"; export default createStore({ state:{ isLogin:true }, mutations:{ SET_ISLOGIN(state,value){ state.isLogin = value } }, actions:{ set_isLogin(context,value){ context.commit('SET_ISLOGIN',value) } }, modules:{} }) Copy the code
Use:
When using useStore to get the value of a Store object from vuex, be aware that you must wrap it using computed so that state changes in vuex can be responded to in the page
Import {useStore} from 'vuex' setup(){const store = useStore() // equivalent to this.$store store.dispatch() // through store MIT () // commit Modify store data let category = computed(() => store.state.isLogin return { category } }Copy the code