Vue3
Vue3优点
1.首次渲染更快
2.diff
Faster algorithms
- Because the virtual dom in vue2 is for full comparison, while in vue3 new static tags are added, only nodes with PF are compared, and the information of Flag is used to know the specific content of the current node to be compared
3. Better in-memory rendering
4. Packed in a smaller size
5. Better TS support
6.template
There is no need to nest a layer of root tags in the
- This is because internally multiple tags will be included in a
Fragment
in the virtual element of , and the element will not be rendered in the dom tree again.
template>
<div>Wuhu</div>.
<div> Takeoff</div>
</template>
- 1
- 2
- 3
- 4
7. Combined APIs.vue2then the option is API; the combined api can improve thesubassembliesReusability Better maintenance
The main file in Vue3 hangs on the component
import { createApp } from 'vue'
import App from './'
// Create an application instance based on the App component
const app = createApp(App)
// app application mounted (managed) #app container
app.mount('#app')
- 1
- 2
- 3
- 4
- 5
- 6
Note: the one in vue3 is using thecreateApp()
Managing containers, notnew Vue()
setup
function (math.)
setup
function is unique to vue3 and serves as a starting point in the api; from the component lifecycle perspective, it is used as a starting point in thebeforeCreate
before executing
function in thethis
is not a component instance, it'sundefined
If the data or function is in thetemplatesThe use of this function requires thesetup
come (or go) back
<template>
<div class="container">
<h1 @click="say()">{{msg}}</h1>
</div>
</template>
<script>
export default {
setup () {
return{}
}
}
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
Note that thesetup
not used inthis
Everything is available through the function
setup
syntactic sugar
To make the code more concise, you can use syntactic sugar; this omits the export configuration item.setup
Function declarations and the need forreturn
digital
<template>
<button @click="toggle"> show hidden image</button>
<img v-show="show" alt="Vue logo" src=". /assets/" /> <img v-show="show" alt="Vue logo" src=".
<hr />
Counter: {{ count }} <button @click="increment">totalization</button>
</template>
<script setup>
// Show hidden
const show = ref(true)
const toggle = () => {
= !
}
// register
const count = ref(0)
const increment = () => {
++
}
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
Attention:script setup
can also be used directly in templates.
reactive
function (math.)
utilizationreactive
define an objectarraysResponsive data of type
Use:
- surname Cong
vue
derived fromreactive
function (math.) - exist
setup
function using thereactive
function, passed a normal object, returns a responsive data object - end up
setup
function returns an object, the inclusion of this responsive object allows the template to use the
<template>
<div>
<p>Name:{{state.name}}</p>
<p>Age:{{state.age}} <button @click="++">over the years</button></p>
</div>
</template>
<script>
// 1. Importing functions
import { reactive } from "vue";
export default {
setup() {
// 2. Creating Responsive Data Objects
const state = reactive({ name: 'tom', age: 18 })
// 3. Return data
return { state }
}
};
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
reactive
Functions typically define complex types of responsive data and cannot convert simple data
ref
function (math.)
Can be used to define responsive data with no restrictions on type
Procedure for use
- surname Cong
vue
derived fromref
function (math.) - exist
setup
function using theref
function, passed plain data (simple OR complex), returns a responsive data - ultimate
setup
It is sufficient for the function to return an object containing this responsive data - Note: The use of
ref
The data created.js
need.value
,template
May be omitted from
<template>
<div>
<p>
Counter: {{ count }}
<button @click="count++">totalization1</button>
<!-- templatemay be omitted when used in.value -->
<button @click="increment">totalization10</button>
</p>
</div>
</template>
<script>
// 1. Import Functions
import { ref } from "vue";
export default {
setup() {
// 2. Creating Responsive Data Objects
const count = ref(0);
const increment = () => {
// jsRequired for use in.value
+= 10;
};
// 3. Return data
return { count, increment };
},
};
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
reactive
together withref
enhancement
reactive
Objects can be converted to be responsive data objects, but simple data types are not supported
ref
Simple data types can be converted to responsive data types, and complex data types are also supported, but the operation of the.value
Recommended: if you can determine that the data type is an object and the field name is determined to be usablereactive
Convert to responsive data, use everything elseref
// 1. Clarify that the form object has two fields
const form = reactive({
username: '',
password: ''
})
// 2. Data objects returned by the backend
const data = ref(null)
const res = await axios.get('/user/100')
data.value = res.data
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
computed
function (math.)
broad steps
- surname Cong
vue
derived fromcomputed
function (math.) - exist
setup
function using thecomputed
function, pass in a function, the function returns the calculated data - ultimate
setup
function returns an object, it's sufficient to include the object's attributes, and then directly use the
<template>
<div>
<p> score: {{ scoreList }}</p>
<p> Excellent: {{ betterList }}</p>
</div>
</template>
<script setup>
import { ref, computed } from "vue";
const scoreList = ref([80, 100, 90, 70, 60]);
// Calculating properties
const betterList = computed(() => ((item) => item >= 90));
// Changing data,Calculating properties改变
setTimeout(() => {
(92, 66);
}, 3000);
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
watch
function (math.)
utilizationwatch
Listen for a responsive data :watch
(data, callback function after change)
<template>
<p> counter: {{ count }}</p>
</template>
<script setup>
import { ref, watch } from "vue";
const count = ref(0);
// 1. Listen for a responsive data
// watch(data, callback function when changed)
watch(count, () => {
("count has changed"); }); {
});
// 2s to change data
setTimeout(() => {
++;
}, 2000); // 2s to change data setTimeout(() => { ++; }
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
utilizationwatch
Listen to multiple sets of responsive data :watch
([data1, data2, ...], callback function after change)
<template>
<p> counter: {{ count }}</p>
</template>
<script setup>
import { ref, watch } from "vue";
const count = ref(0);
const count1 = ref(1);
// 1. Listening to multiple responsive data
// watch([digital1, digital2, ...], Callback function after change)
watch([count,count1], () => {
("countchanged");
});
// 2s改变digital
setTimeout(() => {
++;
}, 2000);
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
utilizationwatch
Listens for a simple property in the responsive object data source :watch
(()=> data, callback function after change)
<template>
<p>
Name: {{ }} Gender: {{ }} Age: {{ }}
</p>
</template>
<script setup>
import { reactive, watch } from "vue"; const user = reactive({ { }}, watch }, watch })
const user = reactive({
name: "tom", {
info: {
gender: "male", age: 18, }
age: 18, }, const user = reactive({ name: "tom", info: { gender: "male", age: 18, }, { user = reactive()
},
}).
// 3. listen for a piece of responsive object data, simple type
// watch(()=> data, callback function when changed)
watch(()=>, () => {
("The data changed");;
});
// 2s to change data
setTimeout(() => {
= 'jack'; }, 2000); // 2s to change data setTimeout(() => {
}, 2000); // 2s change data setTimeout(() => { = 'jack'; }, 2000); // 2s change data
// 4s to change data
setTimeout(() => { {
= 60; }
}, 4000); }
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 使用
watch
监听响应式对象数据中的一个复杂属性,配置深度监听 : watch(()=>数据, 改变后回调函数, {deep: true})
<template>
<p>
name and surname:{{ }} Gender: {{ }} Age: {{ }}
</p>
</template>
<script setup>
import { reactive, watch } from "vue"; const user = reactive({ { }}, watch }, watch })
const user = reactive({
name: "tom", {
info: {
gender: "male", age: 18, }
age: 18, }, const user = reactive({ name: "tom", info: { gender: "male", age: 18, }, { user = reactive()
},
}).
// 4. watch for one of the responsive object data, complex type
// watch(()=> data, callback function when changed, {deep: true})
watch(
() => , () => {
("Data changed"); }
},
{
// Enable deep listening
deep: true, { // Enable deep listening.
// Execute once by default
immediate: true
}
);
// 2s to change data
setTimeout(() => {
= 60; }, 2000); // 2s to change data.
}, 2000); // 2s to change data.
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
Attention:watch( the data to be listened to, the body of the function that performs the data change, the configuration object )
to listen; attribute complexity requires that the deep
lifecycle function
Lifecycle hooks in vue3 can be called multiple times and all start with on.
- Comparison of Vue3 and vue2 lifecycle
Lifecycle Function Usage under the Options API | Lifecycle Function Usage under the Combinatorial API |
---|---|
beforeCreate | Not required (written directly to the setup function) |
created | Not required (written directly to the setup function) |
beforeMount | onBeforeMount |
mounted | onMounted |
beforeUpdate | onBeforeUpdate |
updated | onUpdated |
beforeDestroyed | onBeforeUnmount |
destroyed | onUnmounted |
activated | onActivated |
deactivated | onDeactivated |
Use:
- start with
vue
Importing lifecycle hooks in - exist
setup
The function axis calls the lifecycle hook and passes it back to the function.
<script setup>
import { onMounted } from "vue"; // Lifecycle function.
// Lifecycle function: component rendered
onMounted(()=>{
('onMounted was triggered')
})
onMounted(()=>{
('onMounted also triggered')
})
</script>
<template>
<div> Lifecycle function </div>
</template>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
Note: It is generally common to useonMounted
This is called after the component has been rendered, and can be used to: send a request, operate thedom
et al. (and other authors)
ref
gaindom
causality
element using theref
property associates responsive data, gets theDOM
elemental
Steps:
- establish
ref
- Creating associations in templates
- utilization
<script setup>
import { ref } from 'vue'
const hRef = ref(null)
const clickFn = () => {
= 'I'm not the title.'
}
</script>
<template>
<div>
<h1 ref="hRef">I'm the title.</h1>
<button @click="clickFn">manipulateDOM</button>
</div>
</template>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
Note: If you want to access the value directly, you need to add the value in theonMounted
accessed in the hook, it can't be accessed if you access it directly in the js code, because at that time thedom
Instance object not yet mounted
ref
Examples of manipulation components -defineExpose
If you use the<script setup>
Syntactic sugar, components are turned off by default, and component instance objects don't use top-level data and functions
需要配合defineExpose
来暴露给组件实例对象使用,但是暴露的响应式数据会自动解除响应式
<template>
<h3>我是son组件</h3>
</template>
<script setup>
import { ref } from 'vue'
const count = ref(0)
const validate = () => {
('表单校验方法')
}
// 暴露属性给外部组件使用
defineExpose({count, validate})
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
<template>
<Form ref="formRef"></Form>
</template>
<script setup>
import { ref } from 'vue'
import Form from './components/'
// 1. 提供一个ref
const formRef = ref(null)
// 2. 使用组件组件和方法
const fn = () => {
()
()
}
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
take note of:become man and wife defineExpose
exposing data and methods.ref
The component instances obtained are the only ones that can be used
Father to son -defineProps
function (math.)
move
- Parent component provides data
- Parent component passes data to child component
- The subcomponent passes the
defineProps
carry out acceptance - The child component renders the data passed by the parent component
<template>
<div>
<h1>I am the parent component</h1>
<ChildCom :money="money" :car="car"></ChildCom>
</div>
</template>
<script setup>
import { ref } from 'vue'
import ChildCom from './components/'
const money = ref(100)
const car = ref('Maserati')
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
<template>
<div>
<h3> I am a subcomponent</h3>
<div>{{ money }} --- {{ car }}</div>
</div>
</template>
<script setup>
import { computed } from 'vue'
// defineProps: Receive the data passed by the parent component
const props = defineProps({
money: Number,
car: String,
})
// utilizationprops
()
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
Note: If only thedefineProps
to accept data, this data can only be used in templates; if you want to manipulate the data in subjs, theprops
属性应该接受返回值
子传父 - defineEmits函数
步骤
- 子组件通过
defineEmits
来获取emit
函数 - 子组件通过
emit
Trigger events and pass data - Parent component provides methods
- The parent component registers events to the child component by way of custom events
<template>
<div>I'm a subcomponent.</div>
</template>
<script setup>
// captureemitfunction (math.),Explicitly declaring the event name
const emit = defineEmits(['changeMoney'])
const change = () => {
emit('changeMoney', 10)
}
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
<template>
<div>I'm a subcomponent.</div>
<ChildCom @changeMoney="changeMoney"></ChildCom>
</template>
<script setup>
import { ref } from 'vue'
import ChildCom from './components/'
const changeMoney = (num) => {
(num)
}
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
Cross-level component communicationprovide
together withinject
function (math.)
pass (a bill or inspection etc)provide
respond in singinginject
Functions for easy cross-component communication
move
-
provide
Provide data or functions that descendant components need to rely on -
inject
gainprovide
The data or functions provided
<template>
<div > grandpa component {{ count }}</div>
</template>
<script setup>
import { provide, ref } from 'vue';
import ParentCom from './';
// 1. appThe component data is passed to thechild
const count = ref(0);
provide('count', count);
// 2. appThe component function is passed to thechild,You can pass back data when you call
const updateCount = (num) => {
+= num;
};
provide('updateCount', updateCount);
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
<template>
<div>
grandchildren Component {{ count }}
<button @click="updateCount(100)">modificationscount</button>
</div>
</template>
<script setup>
const count = inject('count');
const updateCount = inject('updateCount');
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
Note: The data is the responsibility of the person who provides it, and the acquiring party cannot modify the data of the providing party.
Stay responsive -toRefs
function (math.)
If you use thereactive
Responsive data created that is expanded or deconstructed loses its responsiveness, and to keep it you need to use thetoRefs
function (math.)
toRefs
will do a wrapping of every property in the object into responsive data
If you are using deconstructed or expanded responsive data objects use thetoRefs
data to maintain responsive
import { reactive, toRefs } from "vue";
const user = reactive({ name: "tom", age: 18 });
const { name, age } = toRefs(user)
- 1
- 2
- 3
Suspense
waiting component
Suspense is used to add some extra content while waiting for an asynchronous component to render, to improve the user experience
// Asynchronous introduction of components
import {defineAsyncComponent} from 'vue'
const Child = defineAsyncComponent(()=>import('./components/'))
// utilization`Suspense`package assembly,and configured`default` together with `fallback`
<template>
<div class="app">
<h3>I am.Appassemblies</h3>
<Suspense>
<template v-slot:default>
<Child/>
</template>
<template v-slot:fallback>
<h3>loading.....</h3>
</template>
</Suspense>
</div>
</template>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
Difference between responsive implementation principles in Vue2 and Vue3
Vue2 uses the(
) performs data hijacking to manipulate reads and modifications
Object.defineProperty(data, 'count', {
get () {},
set () {}
})
- 1
- 2
- 3
- 4
However, there is a problem with adding and deleting attributes and arrays where the direct modification of subscripts does not update the interface.
In vue3 it's the new syntax that uses ES6Proxy()
respond in singingReflect()
rounding out
proxy (proxy): intercepts changes to any attribute of an object, including reading, writing, adding, deleting, and so on.
Reflect: operate on properties in the source object.
new Proxy(data, {
// Intercept read property values
get (target, prop) {
return Reflect.get(target, prop)
},
// Intercept setting property values or adding new properties
set (target, prop, value) {
return Reflect.set(target, prop, value)
},
// Intercept Delete Attribute
deleteProperty (target, prop) {
return Reflect.deleteProperty(target, prop)
}
})
proxy.name = 'tom'
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15