No nonsense with Vue3, get started quickly
Get to know Vue3
1. Vue2 optional API vs Vue3 combined API
<script>
export default {
data(){
return {
count:0
}
},
methods:{
addCount(){
this.count++
}
}
}
</script>
<script setup>
import { ref } from 'vue'
const count = ref(0)
const addCount = ()=> count.value++
</script>
Features:
- Less code
- Decentralized maintenance becomes centralized maintenance
2. Advantages of Vue3
Use create-vue to build a Vue3 project
1. Get to know create-vue
create-vue is Vue's official new scaffolding tool. The bottom layer is switched to vite (the next generation front-end tool chain) to provide extremely fast response for development.
2. Use create-vue to create a project
Prerequisite - Node.js version 16.0 or higher installed
Execute the following command, this command will install and execute create-vue
npm init vue@latest
Become familiar with the project and key documents
Composable API - setup options
1. How to write the setup option and when to execute it
Writing method
<script>
export default {
setup(){
},
beforeCreate(){
}
}
</script>
execution timing
Executed before beforeCreate hook
2. Features of writing code in setup
The data and methods written in the setup function need to be returned in the form of objects at the end before they can be used by the template.
<script>
export default {
setup(){
const message = 'this is message'
const logMessage = ()=>{
console.log(message)
}
// 必须return才可以
return {
message,
logMessage
}
}
}
</script>
3.
Add a setup tag to the script tag. There is no need to write an export statement. The export statement will be added by default.
<script setup>
const message = 'this is message'
const logMessage = ()=>{
console.log(message)
}
</script>
Composable API - reactive and ref functions
1. reactive
Accepts parameters of object type data and returns a responsive object
<script setup>
// 导入
import { reactive } from 'vue'
// 执行函数 传入参数 变量接收
const state = reactive({
msg:'this is msg'
})
const setSate = ()=>{
// 修改数据更新视图
state.msg = 'this is new msg'
}
</script>
<template>
{
{ state.msg }}
<button @click="setState">change msg</button>
</template>
2. ref
Receives data of simple type or object type and returns a responsive object
<script setup>
// 导入
import { ref } from 'vue'
// 执行函数 传入参数 变量接收
const count = ref(0)
const setCount = ()=>{
// 修改数据更新视图必须加上.value
count.value++
}
</script>
<template>
<button @click="setCount">{
{count}}</button>
</template>
3. reactive vs. ref
- are used to generate responsive data
- difference
- Reactive cannot handle simple types of data
- The ref parameter type has better support, but access modification must be done through .value
- The implementation inside the ref function depends on the reactive function
- Recommendations in actual work
- It is recommended to use the ref function to reduce the memory burden. All Xiaotuxian projects use ref.
Composable API - computed
The basic idea of calculated properties is consistent with Vue2. The calculated properties under the combined API only modify the API writing method.
<script setup>
// 导入
import {ref, computed } from 'vue'
// 原始数据
const count = ref(0)
// 计算属性
const doubleCount = computed(()=>count.value * 2)
// 原始数据
const list = ref([1,2,3,4,5,6,7,8])
// 计算属性list
const filterList = computed(item=>item > 2)
</script>
Composable API - watch
Listen for changes in one or more data, and execute the callback function when the data changes. The two additional parameters immediate control are executed immediately, and deep enables deep listening.
1. Listen to a single data
<script setup>
// 1. 导入watch
import { ref, watch } from 'vue'
const count = ref(0)
// 2. 调用watch 侦听变化
watch(count, (newValue, oldValue)=>{
console.log(`count发生了变化,老值为${oldValue},新值为${newValue}`)
})
</script>
2. Listen to multiple data
To listen to multiple data, the first parameter can be rewritten as an array.
<script setup>
// 1. 导入watch
import { ref, watch } from 'vue'
const count = ref(0)
const name = ref('cp')
// 2. 调用watch 侦听变化
watch([count, name], ([newCount, newName],[oldCount,oldName])=>{
console.log(`count或者name变化了,[newCount, newName],[oldCount,oldName])
})
</script>
3. immediate
The callback is triggered immediately when the listener is created, and the callback is continued after the responsive data changes.
<script setup>
// 1. 导入watch
import { ref, watch } from 'vue'
const count = ref(0)
// 2. 调用watch 侦听变化
watch(count, (newValue, oldValue)=>{
console.log(`count发生了变化,老值为${oldValue},新值为${newValue}`)
},{
immediate: true
})
</script>
4. deep
The ref object monitored through watch is shallow listening by default. Directly modifying the nested object properties will not trigger callback execution. You need to enable deep
<script setup>
// 1. 导入watch
import { ref, watch } from 'vue'
const state = ref({ count: 0 })
// 2. 监听对象state
watch(state, ()=>{
console.log('数据变化了')
})
const changeStateByCount = ()=>{
// 直接修改不会引发回调执行
state.value.count++
}
</script>
<script setup>
// 1. 导入watch
import { ref, watch } from 'vue'
const state = ref({ count: 0 })
// 2. 监听对象state 并开启deep
watch(state, ()=>{
console.log('数据变化了')
},{deep:true})
const changeStateByCount = ()=>{
// 此时修改可以触发回调
state.value.count++
}
</script>
Composable API - lifecycle functions
1. Option vs. Combination
2. Basic use of life cycle functions
- Import life cycle functions
- Execute the life cycle function and pass in the callback
<scirpt setup>
import { onMounted } from 'vue'
onMounted(()=>{
// 自定义逻辑
})
</script>
3. Execute multiple times
When the life cycle function is executed multiple times, it will be executed in sequence.
<scirpt setup>
import { onMounted } from 'vue'
onMounted(()=>{
// 自定义逻辑
})
onMounted(()=>{
// 自定义逻辑
})
</script>
Composable API - Parent-Child Communication
1. From father to son
Basic idea
- Bind properties to child components in parent component
- Receive data internally through props options in child components
2. Child Father
Basic idea
- Label the child component in the parent component through @bind event
- The event is triggered inside the subcomponent through the emit method
Composable API - Template Reference
Concept: Get the real DOM object or component instance object through the ref identifier
1. Basic use
Implementation steps:
- Call the ref function to generate a ref object
- Bind the ref object to the tag through the ref identifier
2. defineExpose
By default in
Composable API - provide and inject
1. Function and scene
Top-level components pass data and methods to any bottom-level components to achieve cross-layer component communication.
2. Transfer common data across layers
Implementation steps
- The top-level component provides data through the
provide
function- The underlying component provides data through the
inject
function
3. Pass responsive data across layers
When calling the provide function, the second parameter is set to the ref object
4. Cross-layer transfer method
The top-level component can pass methods to the bottom-level component, and the bottom-level component calls the method to modify the data of the top-level component.
Vue3.3 new features-defineOptions
Background Note:
have
But used
To solve this problem, the two macros defineProps and defineEmits were introduced. But this only solves the two properties of props and emits.
If we want to define the name of the component or other custom attributes, we still have to go back to the original usage - add an ordinary
There will be two
So the defineOptions macro was newly introduced in Vue 3.3. As the name suggests, it is mainly used to define options of the Options API. You can use defineOptions to define any options, except props, emits, expose, slots (because these can be done using defineXXX)
Vue3.3 new features-defineModel
In Vue3, using v-model on a custom component is equivalent to passing a modelValue attribute and triggering the update:modelValue event.
We need to define props first, and then define emits. There is a lot of duplicate code. If you need to modify this value, you also need to manually call the emit function.
So defineModel was born.
To take effect, vite.config.js needs to be configured
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue({
script: {
defineModel: true
}
}),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
}
})