Step:
-
npm install -g @vue/cli
-
vue -V
-
Vue create project-name // To create a project, press Enter to select Vue3.0
-
vue add typescript
-
NPM install [email protected] - save
-
npm install --save ant-design-vue@next
Vue3.0:
1. The setup function
Setup is the entry function in the Composition API and the first function to be used. You can see from console.log that setup is performed before the beforeCreate life cycle (only once)
beforeCreate() {
console.log('beforeCreate executed ');
},
setup() {
console.log('Setup executes');
return {};
},
/ / setup performed
/ / beforeCreate carried out
Copy the code
Setup of execution time can be deduced from this, the component object has not been created, and is not available for this component instance objects, at the moment this is undefined, cannot access to the data/computed by this/the methods/props, However, properties and methods provided by Setup are accessible from Methods.
Note that setup cannot be an async function: since the return value is no longer a return object, but a promise, the data from the return object cannot be used in the template.
– Parameters to setup (props,context)
Props: is an object that holds the data passed by the parent component to the child component and all properties received by the child component using props
Context: a context object that can be deconstructed using es6 syntax setup(props, {attrs, slots, emit})
- Attrs: Gets any objects on the current component tag that do not have properties received by props, equivalent to this.$attrs
- Slots: The object that contains all the incoming slot content, equivalent to this.$slots
- Emit: A function used to distribute custom events, equivalent to this.$emit
Demonstrate attrs and props
/ / the parent component
<template>
<child :msg="msg" msg2='Hahaha' />
</template>
<script lang='ts'>
import { defineComponent, ref } from 'vue';
// Introduce child components
import Child from './components/Child.vue';
export default defineComponent({
name: 'App'.components: {
Child,
},
setup() {
const msg = ref('hello,vue3');
return{ msg, }; }});</script>
/ / child component
<template>
<h2>Child components</h2>
<h3>msg:{{ msg }}</h3>
</template>
<script lang='ts'>
import { defineComponent } from 'vue';
export default defineComponent({
name: 'Child'.props: ['msg'].setup(props, {attrs, slots, emit}) {
console.log('props:', props);//msg: "hello,vue3"
console.log('attrs:', attrs);//msg2: "hahaha"
return{}; }});</script>
Copy the code
Demo emit
/ / the parent component
<template>
<child @show="show" />
</template>
<script lang='ts'>
setup() {
const show = () = > {
console.log('name:'.'hzw');
};
return {
show,
};
},
</script>
/ / child component
<template>
<button>Dispatching events</button>
</template>
<script lang='ts'>
import { defineComponent } from 'vue';
export default defineComponent({
name: 'Child'.setup(props, { emit }) {
const emitFn = () = > {
emit('show');
};
return{ emitFn, }; }});</script>
Copy the code
ref
Define a reactive data (typically used to define a basic type of reactive data Undefined, Null, Boolean, Number, and String)
grammar
const xxx = ref(initValue):
Copy the code
Note: XXX. Value is used to manipulate data in script, but. Value is not needed in templates
Use an example to demonstrate: implement a button that can be clicked to increase the number
<template>
<div>{{count}}</div>
<button @click='updateCount'>increase</button>
</template>
Copy the code
In Vue2
data() {
return {
conunt: 0}; },methods: {
updateCount() {
this.conunt++; }},Copy the code
In Vue3
setup() {
// ref is used to define a responsive data that returns a ref object with a value attribute
// If you need to manipulate data, use the value attribute of the Ref object
const count = ref(0);
function updateCount() {
count.value++;
}
return {
count,
updateCount,
};
},
Copy the code
In Vue2 we get the DOM node through this.$refs, and in Vue3 we get the dom node through ref
You need to add ref=’ XXX ‘to the label, and then setup a ref type with an initial value of null and a name that matches the label’s ref attribute.
Note: Be sure to return in the setup return, otherwise an error will be reported.
reactive
grammar
const proxy = reactive(obj)
Copy the code
A reactive Proxy object that takes a common object and then returns that common object. The reactive transformation is “deep” : it affects all nested properties inside the object, and all data is reactive.
Code demo
<template>
<h3>Name: {{user. The name}}</h3>
<h3>Age: {{user. Age}}</h3>
<h3>wife:{{user.friend}}</h3>
<button @click="updateUser">update</button>
</template>
setup() {
const user = reactive({
name: 'zsy'.age: 18.friend: {
name: 'xiaozhang'.age: 28.books: ['Javascript Essentials you Didn't Know'.'Javacript Advanced Programming '.'Vue Project Practice '],}});const updateUser = () = > {
user.name = 'zhang';
user.age += 2;
user.friend.books[0] = 'The Old Man and the Sea';
};
return {
user,
updateUser,
};
},
Copy the code
The computed function:
Consistent with computed configuration in Vue2, an object of type REF is returned
A function that evaluates a property that passes only one callback represents a GET operation
import { computed } from 'vue';
const user = reactive({
firstName: '张'.lastName: 'ha ha'});const fullName1 = computed(() = > {
return user.firstName + user.lastName;
});
return {
user,
fullName1,
};
Copy the code
A function that evaluates a property can pass in an object that contains set and GET functions to read and modify it
const fullName2 = computed({
get() {
return user.firstName + '_' + user.lastName;
},
set(val: string) {
const names = val.split('_');
user.firstName = names[0];
user.lastName = names[1]; }});return {
user,
fullName2,
};
Copy the code
Watch functions:
- Parameter 1: Data to listen on
- Parameter 2: callback function
- Parameter 3: Configuration
By default, the initial callback is not executed. However, you can specify that the initial callback is executed immediately by setting immediate to true
Deep monitoring is specified by setting deep to true
import { watch, ref } from 'vue';
const user = reactive({
firstName: '张'.lastName: 'ha ha'});const fullName3 = ref(' ');
watch(
user,
({ firstName, lastName }) = > {
fullName3.value = firstName + '_' + lastName;
},
{ immediate: true.deep: true});return {
user,
fullName3,
};
Copy the code
WatchEffect function:
Callbacks are executed when monitoring data changes. Instead of specifying the data to be monitored directly, the reactive data used in the callback function is monitored for the first time, by default, so that the data to be monitored can be collected.
import { watchEffect, ref } from 'vue';
const user = reactive({
firstName: '张'.lastName: 'ha ha'});const fullName4 = ref(' ');
watchEffect(() = > {
fullName4.value = user.firstName + '_' + user.lastName;
});
return{ user, fullName4, }; WatchEffect can be implemented by calculating the property set method watchEffect(() = > {
const names = fullName3.value.split('_');
user.firstName = names[0];
user.lastName = names[1];
});
Copy the code
Life cycle comparison:
Code demo
setup() {
onBeforeMount(() = > {
console.log('--onBeforeMount')
})
onMounted(() = > {
console.log('--onMounted')
})
onBeforeUpdate(() = > {
console.log('--onBeforeUpdate')
})
onUpdated(() = > {
console.log('--onUpdated')
})
onBeforeUnmount(() = > {
console.log('--onBeforeUnmount')
})
onUnmounted(() = > {
console.log('--onUnmounted')})}Copy the code
toRefs
Convert a reactive object into a normal object where each attribute is a ref
application
For objects created by Reactive, if you want to use them in a template, you have to use the form XXX. XXX, which is cumbersome if you use a lot of them. However, when you deconstruct them using ES6, they become unresponsive. ToRefs allows you to convert all raw properties of a reactive object to reactive REF properties.
Code demo
<template>
<div>
name:{{name}}
</div>
</template>
<script lang='ts'>
import { defineComponent, reactive, toRefs } from 'vue';
export default defineComponent({
name: ' '.setup() {
const state = reactive({
name: 'zsy'});const state2 = toRefs(state);
setInterval(() = > {
state.name += '= = =';
}, 1000);
return {
// Deconstructed properties of objects returned through toRefs are also reactive. state2, }; }});</script>
Copy the code
Dojo.provide and inject
Function To communicate between components (grandparents and grandchildren) across hierarchies
Code demo
The parent component
<template>
<h1>The parent component</h1>
<p>Current color: {{color}}</p>
<button @click="color='red'">red</button>
<button @click="color='yellow'">huang</button>
<button @click="color='blue'">blue</button>
<hr>
<Son />
</template>
<script lang="ts">
import { provide, ref } from 'vue'
import Son from './Son.vue'
export default {
name: 'ProvideInject'.components: {
Son
},
setup() {
const color = ref('red')
provide('color', color)
return {
color
}
}
}
</script>
Copy the code
Child components
<template>
<div>
<h2>Child components</h2>
<hr>
<GrandSon />
</div>
</template>
<script lang="ts">
import GrandSon from './GrandSon.vue'
export default {
components: {
GrandSon
},
}
</script>
Copy the code
The grandson components
<template>
<h3 :style="{color}">{{color}}</h3>
</template>
<script lang="ts">
import { inject } from 'vue'
export default {
setup() {
const color = inject('color')
return {
color
}
}
}
</script>
Copy the code
Vue3.0 ecology:
- website
- The source code
- The scaffold
- vue-router@4
- vuex@4
Vue3.0 association can use the UI:
- element-plus
- Ant Design of Vue 2.x
- vant2.x