This is the 14th day of my participation in Gwen Challenge
Environment set up
- Uvu has developed a project building tool called Vite
npm init vite-app <project-name>
cd <project-name>
npm install
npm run dev
Copy the code
Create an instance
- Vue3 added a new method — creatApp — to create the instance, instead of creating it as a new Vue({})
import {createApp} from 'vue'
const app =createApp({})
////////////////////////
import {
createApp
} from 'vue'
import App from './App.vue'
const app = createApp(App)
app.mount('#app')
Copy the code
<template> <! X :{{position.x}} y:{{position.y}}</h1> </template> <script> import { reactive } from 'vue'; // import HelloWorld from './components/HelloWorld.vue'; Export default {name: 'App', // components: {// HelloWorld //}, setup() {reactive({}); // Build a response object window.addEventListener('mousemove', e => {position.x = e.pagex; position.y = e.pageY; // console.log(position); }); return { position }; // Finally expose the data}}; </script>Copy the code
Optional and composite apis
- Solve the problem of split logical concerns
Vue2: Optional API,
Vue3: Composite API, written in setup() without this
export default {
name: 'App'.// components: {
// HelloWorld
// },
setup() { // Data entry
console.log('Setup this is'.this) // Output: setup this is undefined
let position = reactive({}); // Build responsive objects
window.addEventListener('mousemove'.e= > {
position.x = e.pageX;
position.y = e.pageY;
// console.log(position);
});
return { position }; // Finally expose the data}};Copy the code
ref
Create a reactive variable
const time = ref(0); // Create a variable of value type number stringCopy the code
unref
If the argument is ref, the internal value is returned, otherwise the argument itself is returned. This is val = isRef(val), right? Val. Value: val.
function useFoo(x: number | Ref<number>) {
const unwrapped = unref(x) // unwrapped ensures that it is now a numeric type
}
Copy the code
reactive
- There is one in VUe2
Vue.observable
Method to return a responsible object. In vue2, the data function returns an object, which is used internally in VUEVue.observable
To deal with
const position = reactive({
// Create response object
x: 0.y: 0.visible:props.visible,
info: computed(() = > {
return 'Current position in X:${position.x} Y:${position.y}`; })});Copy the code
toRef
You can use it to create a REF for a property on a source reactive object. You can then pass the REF out, preserving a reactive connection to its source property.
const state = reactive({
foo: 1.bar: 2
})
// Create variables in three ways
const fooToRef = toRef(state, "foo"); // fooToRef++ can respond to state. Foo changing at the same time
const fooRef = ref(state.foo); // None Stata remains unchanged
let foo = state.foo;// None Stata remains unchanged
Copy the code
As can be seen from the above small test, toRef is to establish a reference relationship between a variable and a responsive object. When the variable changes, the source response object can be changed
toRefs
Refer to the address
- Action: Makes the values in props responsive
The props passed in is reactive, updated in real time, and passed to Setup for immediate use
export default {
props: {
title: String
},
setup(props) {
console.log(props.title)
}
}
Copy the code
Each call to the properties in props needs to be in the form of props.[Property name], which is complicated to write, considering the deconstruction assignment in ES6
But using ES6 deconstruction eliminates the responsiveness of prop, so toRefs is used to simplify writing
props:{
user:{
type:String
}
}
import{toRefs} 'vue'
const { user } = toRefs(props)
Copy the code
watch
Listening for common types
let count = ref(1);
const changeCount = () = > {
count.value+=1
};
watch(count, (newValue, oldValue) = > { // Direct listener
console.log("Count has changed.");
});
Copy the code
Listen for reactive objects
let book = reactive({
name: "Js programming".price: 50});const changeBookName = () = > {
book.name = "c#";
};
watch(() = >book.name,() = >{// Returns the attribute to listen on via a function
console.log('Title changed')})Copy the code
Listen for multiple arguments to execute different methods
But these are just some simple examples. In VUe2, Watch can listen to multiple sources and perform different functions
- Note: I learned the method when I consulted others in the group, but I did not find it in the official document. if there is any mistake, I hope to be criticized and corrected
In VUe3, the same scenario can also be realized through multiple Watches, but in VUe2, only one watch can exist
watch(count, () = > {
console.log("Count has changed.");
});
watch(
() = > book.name,
() = > {
console.log("The title has changed."); });Copy the code
Listen for multiple arguments to perform the same method
There may be cases in VUe2 where you need to perform the same events, and the solution is usually to store them in an object using computed and listen for changes in that object
For VUE3, you can dispense with computed operations
watch([() = > book.name, count], ([name, count], [preName, preCount]) = > {
console.log("Count or book.name changed");
});
Copy the code
watchEffect
- There is no need to specify a listening attribute, as long as the response attribute is introduced in the callback, and the response event is automatically triggered when the attribute changes
watchEffect(()=>{
console.log(count)
})
Copy the code
The life cycle
Option type API | Hook inside setup |
---|---|
beforeCreate |
Not needed* |
created |
Not needed* |
beforeMount |
onBeforeMount |
mounted |
onMounted |
beforeUpdate |
onBeforeUpdate |
updated |
onUpdated |
beforeUnmount |
onBeforeUnmount |
unmounted |
onUnmounted |
errorCaptured |
onErrorCaptured |
renderTracked |
onRenderTracked |
renderTriggered |
onRenderTriggered |