1. Start
Vue3.0 has been released and used for a period of time, I feel that Vue3.0 is relatively easy to use, especially the Composition API is relatively smooth to use, compared with the Options API of Vue2.0 is relatively clear, reducing the trouble of switching back and forth. Improved readability and maintainability.
The following two images clearly illustrate the differences between the two apis, and you should definitely choose Composition API😄
Take a look at the Options API for VUe2.0
Take a look at the Vue3.0 Composition API
If you’re still a little confused, let’s move on to the next example.
Let’s take a look at the way Vue2 is written:
export default {
data() {
return {
list: [{title: 'VueJS'.name: 'learning Vue'.id: 1 },
{ title: 'ReactJS'.name: 'learning React'.id: 2 },
{ title: 'AngularJS'.name: 'learning presents'.id: 3},]}; },methods: {
addItem() {
this.list.push({ title: 'NodeJs'.name: 'learning Node' });
},
deleteItem(id) {
this.list = this.list.filter((item) = >item.id ! == id); ,}}};Copy the code
Here’s how Vue3 is written:
import { ref } from 'vue';
export default {
setup() {
const list = ref([
{ title: 'VueJS'.name: 'learning Vue'.id: 1 },
{ title: 'ReactJS'.name: 'learning React'.id: 2 },
{ title: 'AngularJS'.name: 'learning presents'.id: 3},]);const addItem = () = > {
list.value.push({ title: 'NodeJs'.name: 'learning Node' });
};
const deleteItem = (id) = > {
list.value = list.value.filter((item) = >item.id ! == id); };return{ list, addItem, deleteItem, }; }};Copy the code
Compared to Vue2 syntax, Vue3 is simple and convenient to write, saving us time to switch back and forth.
2. Create projects
If you want to get excited about this, let’s set up the development environment.
We can build Vue3 projects using Vue CLI or Vite2.
For details, please check out the instructions for building Vue3.0 projects with VitE2. I won’t go into details here.
Use 3.
Let’s first take a look at Vue3 Chinese document to understand the basic syntax of Vue3. Compared with Vue2, there are still great changes.
If you don’t want to see the documentation, you can also check out the experience Vue3.0
4. Development optimization
1. script setup
If you don’t want to return a variable without using it, you can use setup
<script>
import { reactive } from 'vue';
export default {
props: { msg: String },
setup() {
const state = reactive({ count: 0 });
const addCount = () = > {
state.count++;
};
return{ state, addCount, }; }}; </script>Copy the code
Use script Setup ↓↓
<script setup>
import { defineProps, reactive } from 'vue';
import Test from './Test.vue';
defineProps({
msg: String});const state = reactive({ count: 0 });
const addCount = () = > {
state.count++;
};
</script>
Copy the code
More usage: details
2. style
export default {
setup() {
const state = reactive({
fontSize: 20.color: 'red'});return{... toRefs(state), }; }}; </script><style lang="scss" scoped>
.color-style{
color: v-bind(color);
font-size: v-bind(fontSize);
}
</style>
Copy the code
3. V – model parameters
Take a look at the demo on the official website
<ChildComponent v-model:title="pageTitle" />
<! -- is short for: -->
<ChildComponent :title="pageTitle" @update:title="pageTitle = $event" />
Copy the code
The.sync modifier is deprecated. If you want to send values asynchronously, use v-model:[params]
In Vue2, one component, v-Model, specifies a value to bind to. In Vue3, v-Model can bind to multiple values, which is very convenient for us to obtain multiple values dynamically at the same time.
The parent component:
# parent.vue <template> <childCom v-model:value="parentValue" v-model:title="parentTitle"/> </template> <script> import { ref } from 'vue'; import childCom from './childCom.vue'; export default { components: { childCom }, setup() { const parentValue = ref(''); const parentTitle = ref(''); return { parentValue, parentTitle }; }}; </script> <style lang="scss" scoped> </style>Copy the code
Child components:
# childCom.vue
<template>
<input type="text" :value="value" @input="changeValue"> <br>
<span>{{ text }}</span>
<button @click="clickButton">
plus
</button>
</template>
<script>
import { reactive, toRefs } from 'vue';
export default {
name: 'BaseInput',
props: {
value: {
type: [String, Number],
default: '',
},
text: {
type: [String, Number], default: '测试',
},
},
emits: ['update:value', 'input', 'update:text'],
setup(props, context) {
const state = reactive({
textTest: '测试',
});
const changeValue = (e) => {
context.emit('update:value', e.target.value);
context.emit('input', e.target.value);
};
const clickButton = () => {
context.emit('update:text', Math.random() * 100);
};
return { ...toRefs(state), changeValue, clickButton };
},
};
</script>
<style>
</style>
Copy the code
4. Composition API
Let’s start with our toDOS logic
<script>
import { reactive, toRefs } from 'vue';
export default {
setup() {
const state = reactive({
list: [{title: 'VueJS'.name: 'learning Vue'.id: 1 },
{ title: 'ReactJS'.name: 'learning React'.id: 2 },
{ title: 'AngularJS'.name: 'learning presents'.id: 3},]});const addItem = () = > {
state.list.push({ title: 'NodeJs'.name: 'learning Node' });
};
const deleteItem = (id) = > {
state.list = state.list.filter((item) = >item.id ! == id); };const getLength = (list) = > list.length;
return{... toRefs(state), addItem, deleteItem, getLength, }; }}; </script>Copy the code
We can remove the logic or some other modules, and really achieve the combined API, which is convenient for the maintenance of our code in the future. We can directly locate the problem and find the module to modify, without affecting other logic.
A quick implementation:
// test.js
import { reactive, toRefs } from 'vue';
export default function () {
const state = reactive({
list: [{title: 'VueJS'.name: 'learning Vue'.id: 1 },
{ title: 'ReactJS'.name: 'learning React'.id: 2 },
{ title: 'AngularJS'.name: 'learning presents'.id: 3},]});const addItem = () = > {
state.list.push({ title: 'NodeJs'.name: 'learning Node' });
};
const deleteItem = (id) = > {
state.list = state.list.filter((item) = >item.id ! == id); };const getLength = (list) = > list.length;
return {
state, addItem, deleteItem, getLength,
};
}
Copy the code
<script>
import { toRefs } from 'vue';
import useTest from './test';
export default {
setup() {
const {
state, addItem, deleteItem, getLength,
} = useTest();
return{... toRefs(state), addItem, deleteItem, getLength, }; }}; </script>Copy the code
This Mixins is similar to Vue2 Mixins, but its biggest advantage is that we can clearly see all the introduced functions and parameter names and paths, avoiding the problem of using the same parameter name pollution. Clear, truly load the required functions on demand, improve performance optimization and rendering speed.
5. Change
1. $attrs
Vue2
When using inheritAttrs: false, there are side effects:
- Instead of attributes in $attrs being automatically added to the root element, the developer decides where to add them
- But class and style are not part of $attrs and are still applied to the root element of the component:
Vue3
In a component that uses inheritAttrs: False, make sure the style is still as expected. If you had relied on the special behavior of class and style, you might have broken some of the visuals because those attributes might now be applied to another element.
$attrs contains all the attributes passed to the component, including class and style
2. $listeners
The $Listeners object has been removed from Vue3 and now listens for event listeners as part of $attrs
3. $children
The $children instance property has been removed from Vue 3.0, and $ref is recommended for fetching elements
4. Customize commands
Vue2
- Occurs after the bind-instruction is bound to an element. It only happens once.
- Inserted – Occurs after the element is inserted into the parent DOM.
- Update – This hook is called when the element is updated, but the child elements have not been updated.
- ComponentUpdated – This hook is called as soon as components and children are updated.
- Unbind – This hook is called once the instruction is removed. It’s only called once.
Vue3
- Created – New! Called before an element’s attribute or event listener is applied.
- The bind – beforeMount
- He inserted – mounted
- BeforeUpdate: New! This is called before the element itself is updated, much like a component lifecycle hook.
- Update → Remove! There are too many similarities to update, so this is redundant, please use updated instead.
- ComponentUpdated – updated
- BeforeUnmount: New! Similar to a component lifecycle hook, it is called before an element is unloaded.
- unbind -> unmounted
5. The filter
As of Vue 3.0, filters have been removed and are no longer supported. It is recommended to replace filters with computed properties or methods
Global filters can also be used
If a filter is registered globally in your application, it may not be convenient to replace it with computed properties or method calls in each component
// main.js
const app = createApp(App)
app.config.globalProperties.$filters = {
currencyUSD(value) {
return '$' + value
}
}
Copy the code
<template>
<h1>Bank Account Balance</h1>
<p>{{ $filters.currencyUSD(accountBalance) }}</p>
</template>
Copy the code
Note: This approach can only be used in methods, not computed properties, because it only makes sense when defined in the context of a single component.
Others are being summarized and will continue to be updated…