vite
Youda 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 create a vue3 project
Vite is a modern browser-oriented web development and construction tool based on the native module system ESModule. Packaging based on Rollup in production environment
- Quick Cold Start Server
- Instant thermal module replacement (HMR)
- True on-demand compilation
node >= 10.16.0
Build
Use vite to build a project
npm init vite-app <project-name>
Install typescript,vue-router@next, axios, eslint-plugin-vue, sass and other related plugins
Configuration
Equivalent to the @vue-cli project
I'll configure it simply:
import path from 'path' = { alias: { '/@/': (__dirname, './src') }, optimizeDeps: { include: ['lodash'] }, proxy: {} }
Router
Create a new router folder under src and create it in the folder
import { createRouter, createWebHistory } from 'vue-router' const routes = [ { path: '/', name: 'Home', component: () => import('/@/views/') }, { path: '/lifeCycle', name: 'lifeCycle', component: () => import('/@/views/') } ] export default createRouter({ history: createWebHistory('/krry/'), routes })
ts types
Create a new project root directory and write related configuration
{ "compilerOptions": { ...// Other configurations "paths": { "/@/*": [ "src/*" ] }, "lib": [ "esnext", "dom", "", "scripthost" ] }, "include": [ "src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "src/types/", "tests/**/*.ts", "tests/**/*.tsx" ], "exclude": [ "node_modules" ] }
Create a new type folder in the src directory, and you need to configure the type of ts in it
declare module '*.vue' {}
declare module '*.svg' declare module '*.png' declare module '*.jpg' declare module '*.jpeg' declare module '*.gif' declare module '*.bmp' declare module '*.tiff'
import { createApp } from 'vue' import router from '/@/router' import App from '/@/' const app = createApp(App) (router) ('#app')
Then you can write the code happily
vue3 knowledge
setup
In vue3, the setup function is used to integrate all APIs; it is executed only once and is executed before the lifecycle function, so the current instance cannot be obtained in the setup function. This cannot be used to call the method defined in the vue2 writing method
It will accept two parameters: props, context
// props - property accepted by the component - contextsetup(props, context) { return { // Data and methods to bind } }
props
The props in the setup function are responsive and will be updated when a new prop is passed in
However, because props are responsive, it cannot be deconstructed using ES6 because it eliminates the responsiveness of props
If you need to deconstruct the prop, you can do this safely by using toRefs in the setup function
import { toRefs } from 'vue' setup(props) { const { title } = toRefs(props) () }
context
context exposes the property of three components: { attrs, slots, emit }
It is a normal JavaScript object, not responsive, which means you can safely deconstruct the context using ES6
life cycle
Access the component's life cycle hook by prefixing the life cycle hook
Because setup runs around beforeCreate and created lifecycle hooks, they don't need to be explicitly defined
In other words, any code written in these two hooks should be written directly in the setup function
setup() { onMounted(() => { ('Component Mount') }) onUnmounted(() => { ('Component Uninstall') }) onUpdated(() => { ('Component Update') }) onBeforeUpdate(() => { ('Components are about to be updated') }) onActivated(() => { ('keepAlive component Activate') }) onDeactivated(() => { ('keepAlive component is not activated') }) return {} }
ref、reactive
ref can wrap a normal value into responsive data, limited to simple values, and internally wrap the value into an object and then process it through defineProperty
When selecting and setting values through ref, you need to use .value to set them
You can use ref to get the reference of the component instead of writing this.$refs
reactive performs responsive processing of complex data. Its return value is a proxy object. When returning in the setup function, you can use toRefs to structure the proxy object for easy use in template
Use as follows:
<template> <div> <div> <ul v-for="ele in eleList" :key=""> <li>{{ }}</li> </ul> <button @click="addEle">Add to</button> </div> <div> <ul v-for="ele in todoList" :key=""> <li>{{ }}</li> </ul> <button @click="addTodo">Add to</button> </div> </div> </template> <script> import { ref, reactive, toRefs } from 'vue' export default { setup() { // ref const eleList = ref([]) function addEle() { let len = ({ id: len, name: 'ref increases by itself' + len }) } // reactive const dataObj = reactive({ todoList: [] }) function addTodo() { let len = ({ id: len, name: 'reactive self-increase' + len }) } return { eleList, addEle, addTodo, ...toRefs(dataObj) } } } </script>
computed、watch
// computed let sum = computed(() => + ) ('setup reference computed to .value:' + ) // watch watch( eleList, (curVal, oldVal) => { ('Listener:', curVal, oldVal) }, { deep: true } )
watchEffect
Responsively tracks the responsive data referenced in the function. When the responsive data changes, the function will be executed again.
const count = ref(0) // When the value of count is modified, a callback will be executedconst stop = watchEffect(() => ()) // Stop monitoringstop()
You can also stop listening, watchEffect returns a function, and you can stop listening after execution.
Same as vue2:
const unwatch = this.$watch('say', curVal => {}) // Stop monitoringunwatch()
useRoute、useRouter
import {useRoute, useRouter} from 'vue-router' const route = useRoute() // equivalent to this.$route in vue2const router = useRouter() // equivalent to this.$router in vue2
route Used to obtain the current routing data
router for routing jump
vuex
When using useStore to get the store object when taking values from vuex, be careful to use computed for wrapping, so that the status in vuex can only be responded in the page after it is modified.
import {useStore} from 'vuex' setup(){ const store = useStore() // equivalent to this.$store in vue2 () // Dispatch asynchronous tasks through the store object () // commit modify store data let category = computed(() => return { category } }
This is the article about the quick construction of vite+ts vue3 projects and introducing related features. For more related content on vite+ts vue3, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!