Detailed explanation of vite+ts to quickly build vue3 project and introduce related features

  • 2021-10-27 06:25:56
  • OfStack

Directory vite
Build
Configure
vite.config.ts
Router
ts types
vue3 Knowledge
setup
props
context
Life cycle
ref, reactive
computed, watch
watchEffect
useRoute, useRouter
vuex

vite

You Da recommended vite tools in Vue 3.0 beta live broadcast, emphasizing that the unpackaged development server for Vue single-page components can directly run the requested vue files in the browser

Very novel, this blog uses it to build a project of vue3 to try

Vite is an Web development and construction tool for modern browsers, which is compiled on demand based on native module system ESModule. Packaging based on Rollup in production environment

Quick cold start server Instant Thermal Module Replacement (HMR) True compile on demand

node > = 10.16.0

Build

Building a project with vite


npm init vite-app <project-name>

Install typescript, vue-router @ next, axios, eslint-plugin-vue, sass and other related plug-ins

Configure

vite.config.ts

vite. config. ts is equivalent to vue.config.js in the @ vue-cli project

My simple configuration is 1:


import path from 'path'

module.exports = {
 alias: {
 '/@/': path.resolve(__dirname, './src')
 },
 optimizeDeps: {
 include: ['lodash']
 },
 proxy: {}
}

Router

Create a new router folder under src and create index. ts in the 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')
 }
]

export default createRouter({
 history: createWebHistory('/krry/'),
 routes
})

ts types

Create new tsconfig. json write related configuration under the root directory of the project


{
 "compilerOptions": {
 ...//  Other configurations 
 "paths": {
  "/@/*": [
  "src/*"
  ]
 },
 "lib": [
  "esnext",
  "dom",
  "dom.iterable",
  "scripthost"
 ]
 },
 "include": [
 "src/**/*.ts",
 "src/**/*.tsx",
 "src/**/*.vue",
 "src/types/images.d.ts",
 "tests/**/*.ts",
 "tests/**/*.tsx"
 ],
 "exclude": [
 "node_modules"
 ]
}

Create a new types folder under the src directory, in which you need to configure the type of ts

shims-vue.d.ts


declare module '*.vue' {}

images.d.ts


declare module '*.svg'
declare module '*.png'
declare module '*.jpg'
declare module '*.jpeg'
declare module '*.gif'
declare module '*.bmp'
declare module '*.tiff'

main.ts


import { createApp } from 'vue'
import router from '/@/router'

import App from '/@/App.vue'

const app = createApp(App)
app.use(router)
app.mount('#app')

Then you can write code happily

vue3 Knowledge

setup

In vue3, all api are integrated with setup function; Execute only once, before the life cycle function, so the current instance this can not be found in the setup function, and the method defined in vue2 can not be called with this

It takes two parameters: props, context


// props -  Attributes received by the component  context -  Context  
setup(props, context) {
 return {
 //  Data and methods to bind 
 }
}

props

The props in the setup function is responsive and will be updated when a new prop is passed in
However, because props is responsive, ES6 deconstruction cannot be used because it eliminates the responsiveness of prop

If you need to deconstruct 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)
}

context

context exposes property of 3 components: {attrs, slots, emit}
It is a normal JavaScript object and is not responsive, which means that you can safely use ES 6 deconstruction for context

Life cycle

Access the lifecycle hook of a component by preceding the lifecycle hook with "on"

Because setup runs around beforeCreate and created lifecycle hooks, there is no need to explicitly define them
In other words, any code written in these two hooks should be written directly in the setup function


setup() {
 onMounted(() => {
 console.log(' Component mount ')
 })

 onUnmounted(() => {
 console.log(' Component uninstall ')
 })

 onUpdated(() => {
 console.log(' Component update ')
 })

 onBeforeUpdate(() => {
 console.log(' Component will be updated ')
 })

 onActivated(() => {
 console.log('keepAlive  Component   Activate ')
 })

 onDeactivated(() => {
 console.log('keepAlive  Component   Inactive ')
 })

 return {}
}

ref, reactive

ref can wrap a common value into responsive data, which is limited to simple values. Inside, the value is wrapped into an object, and then processed by defineProperty
When wrapping the value through ref, you need to set it through. value when taking and setting the value
Instead of this, you can use ref to get a reference to a component. $refs

reactive is responsive to complex data, and its return value is an proxy object. When returning in setup function, toRefs can be used to construct proxy object, which is convenient to use in template

Use the following:


import path from 'path'

module.exports = {
 alias: {
 '/@/': path.resolve(__dirname, './src')
 },
 optimizeDeps: {
 include: ['lodash']
 },
 proxy: {}
}

0

computed, watch


import path from 'path'

module.exports = {
 alias: {
 '/@/': path.resolve(__dirname, './src')
 },
 optimizeDeps: {
 include: ['lodash']
 },
 proxy: {}
}

1

watchEffect

Responsively tracks the responsive data referenced in the function, and when the responsive data changes, the function is re-executed


import path from 'path'

module.exports = {
 alias: {
 '/@/': path.resolve(__dirname, './src')
 },
 optimizeDeps: {
 include: ['lodash']
 },
 proxy: {}
}

2

You can also stop listening. watchEffect returns 1 function, and you can stop listening after execution

Like vue2 1:


const unwatch = this.$watch('say', curVal => {})

//  Stop listening 
unwatch()

useRoute, useRouter


import path from 'path'

module.exports = {
 alias: {
 '/@/': path.resolve(__dirname, './src')
 },
 optimizeDeps: {
 include: ['lodash']
 },
 proxy: {}
}

4

route is used to get the current routing data
router for routing jump

vuex

When using useStore to get the value of an store object from vuex, it should be noted that computed must be used for wrapping, so that the state in vuex can be modified before it can respond in the page


import path from 'path'

module.exports = {
 alias: {
 '/@/': path.resolve(__dirname, './src')
 },
 optimizeDeps: {
 include: ['lodash']
 },
 proxy: {}
}

5

Related articles: