current position:Home>Vue3 learning notes - custom instructions and routing
Vue3 learning notes - custom instructions and routing
2021-08-27 09:39:46 【Front end sophomore】
Vue3 Custom instruction
In addition to the core instructions set by default ( v-model and v-show ), Vue It is also allowed to register custom instructions .
Let's register a global instruction v-focus, The function of this instruction is to , Element gets focus :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue Test case </title>
<script src="https://unpkg.com/[email protected]"></script>
</head>
<body>
<div id="app">
<p> When the page loads ,input Element gets focus automatically :</p>
<input v-focus>
</div>
<script>
const app = Vue.createApp({})
// Register a global custom directive `v-focus`
app.directive('focus', {
// When the bound element is mounted to DOM In the middle of the day ……
mounted(el) {
// Focusing on the element
el.focus()
}
})
app.mount('#app')
</script>
</body>
</html>
Copy code
We can also use... In the example directives Option to register local instructions , This instruction can only be used in this instance :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue Test case </title>
<script src="https://unpkg.com/[email protected]"></script>
</head>
<body>
<div id="app">
<p> When the page loads ,input Element gets focus automatically :</p>
<input v-focus>
</div>
<script>
const app = {
data() {
return {
}
},
directives: {
focus: {
// Definition of instruction
mounted(el) {
el.focus()
}
}
}
}
Vue.createApp(app).mount('#app')
</script>
</body>
</html>
Copy code
hook
Hook function
The instruction definition function provides several hook functions ( Optional ):
created
: Call before the property of the binding element or event listener is applied. .beforeMount
: The instruction is bound to the element for the first time and is called before mounting the parent component. ..mounted
: After the parent component of the binding element is mounted, it is called. ..beforeUpdate
: When updating the containing components VNode Previous call ..updated
: In the VNode And its subcomponents VNode Call after update .beforeUnmount
: When the instruction is unbound from the element and the parent component is unloaded , Call it once .unmounted
: When the instruction is unbound from the element and the parent component is unloaded , Call it once .
import { createApp } from 'vue'
const app = createApp({})
// register app.directive('my-directive', {
// An instruction is a hook with a set of lifecycles :
// At the end of the binding element attribute Call before event listener is applied
created() {},
// Call before the parent component of the binding element is mounted.
beforeMount() {},
// Called when the parent component of a binding element is mounted
mounted() {},
// In the VNode Call before updating
beforeUpdate() {},
// In the VNode And its subcomponents VNode Call after update
updated() {},
// Calls before the parent component of the binding element is uninstalled
beforeUnmount() {},
// Called when the parent component of a binding element is unloaded
unmounted() {} })
// register ( Functional instructions )
app.directive('my-directive', () => {
// This will be used as `mounted` and `updated` call })
// getter, If registered , Returns the instruction definition
const myDirective = app.directive('my-directive')
Copy code
Hook function parameters
The parameters of the hook function are :
el
el The element to which the instruction is bound . This can be used for direct operation DOM.
binding
binding It's an object , Contains the following properties :
instance
: Component instances using instructions .value
: The value passed to the instruction . for example , stayv-my-directive="1 + 1"
in , The value is2
.oldValue
: Previous value , Only inbeforeUpdate
andupdated
Available in the . Whether the value has been changed is available .arg
: Parameters are passed to the instruction ( If there is ). For example, inv-my-directive:foo
in ,arg by"foo"
.modifiers
: Include modifier ( If there is ) The object of . For example, inv-my-directive.foo.bar
in , Modifier object is{foo: true,bar: true}
.dir
: An object , Passed as an argument when registering an instruction . for example , In the following instructions :
app.directive('focus', {
mounted(el) {
el.focus()
}
})
Copy code
dir Will be the following :
{
mounted(el) {
el.focus()
}
}
Copy code
vnode
As el Parameter received true DOM Blueprint of elements .
prevNode
Previous virtual node , Only in beforeUpdate and updated Available in hook .
The following example demonstrates the use of these parameters :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue Test case </title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.0.5/vue.global.js"></script>
</head>
<body>
<div id="app">
<div v-runoob="{ name: ' Baidu ', url: 'www.baidu.com' }"></div>
</div>
<script>
const app = Vue.createApp({})
app.directive('runoob', (el, binding, vnode) => {
console.log(binding.value.name) // => " Baidu "
console.log(binding.value.url) // => "www.baidu.com"
var s = JSON.stringify
el.innerHTML = s(binding.value)
})
app.mount('#app')
</script>
</body>
</html>
Copy code
Sometimes we don't need other hook functions , We can abbreviate functions , The following format :
Vue.directive('runoob', function (el, binding) {
// Set the background color of the command
el.style.backgroundColor = binding.value.color
})
Copy code
The instruction function can accept all legal JavaScript expression , The following instance passed in JavaScript object :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue Test case </title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.0.5/vue.global.js"></script>
</head>
<body>
<div id="app">
<div v-runoob="{ color: 'green', text: ' Baidu !' }"></div>
</div>
<script>
const app = Vue.createApp({})
app.directive('runoob', (el, binding, vnode) => {
el.innerHTML = binding.value.text
el.style.backgroundColor = binding.value.color
})
app.mount('#app')
</script>
</body>
</html>
Copy code
Vue3 route
Vue Routing allows us to go through different URL Access different content .
adopt Vue It can realize multi view single page Web application (single page web application,SPA).
Vue.js The route needs to be loaded vue-router library
Chinese document address :vue-router file .
install
1、 Direct download / CDN
https://unpkg.com/[email protected]
Copy code
NPM
Taobao image is recommended :
npm install -g cnpm --registry=https://registry.npm.taobao.org
cnpm install [email protected]
Copy code
Simple example
Vue.js + vue-router Can be very simple to achieve a single page application .
<router-link>
Is a component , This component is used to set up a navigation link , Switching is different HTML Content . to Property is the target address , What to show .
In the following example, we will vue-router Add in , Then configure the components and route mapping , Tell me again vue-router Where to render them . The code is as follows :
HTML Code :
<script src="https://unpkg.com/[email protected]"></script>
<script src="https://unpkg.com/[email protected]"></script>
<div id="app">
<h1>Hello App!</h1>
<p>
<!-- Use router-link Components for navigation -->
<!-- By passing `to` To specify the link -->
<!--`<router-link>` A with the correct `href` Attribute `<a>` label -->
<router-link to="/">Go to Home</router-link>
<router-link to="/about">Go to About</router-link>
</p>
<!-- Route exit -->
<!-- The component to which the route matches is rendered here -->
<router-view></router-view>
</div>
Copy code
router-link
Please note that , We don't use regular a label , Instead, use a custom component router-link To create a link . This makes Vue Router It can be changed without reloading the page URL, Handle URL Generation and coding of . We'll see how to benefit from these features later .
router-view
router-view Will display with url Corresponding components . You can put it anywhere , To fit your layout .
JavaScript Code :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue Test case </title>
<script src="https://unpkg.com/[email protected]"></script>
<script src="https://unpkg.com/[email protected]"></script>
</head>
<body>
<div id="app">
<h1>Hello App!</h1>
<p>
<!-- Use router-link Components for navigation -->
<!-- By passing `to` To specify the link -->
<!--`<router-link>` A with the correct `href` Attribute `<a>` label -->
<router-link to="/">Go to Home</router-link>
<router-link to="/about">Go to About</router-link>
</p>
<!-- Route exit -->
<!-- The component to which the route matches is rendered here -->
<router-view></router-view>
</div>
<script>
// 1. Define routing components .
// You can also import from other files
const Home = { template: '<div>Home</div>' }
const About = { template: '<div>About</div>' }
// 2. Define some routes
// Each route needs to be mapped to a component .
// We will discuss nested routing later .
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
]
// 3. Create a routing instance and pass `routes` To configure
// You can enter more configurations here , But we're here
// Keep it simple for a while
const router = VueRouter.createRouter({
// 4. The interior provides history The realization of pattern . For the sake of simplicity , We use it here hash Pattern .
history: VueRouter.createWebHashHistory(),
routes, // `routes: routes` Abbreviation
})
// 5. Create and mount the root instance
const app = Vue.createApp({})
// Make sure _use_ Routing instance makes
// The whole application supports routing .
app.use(router)
app.mount('#app')
// Now? , The app has started !
</script>
</body>
</html>
Copy code
Click on the navigation links will be added to the style class ="router-link-exact-active router-link-active".
Related properties
Next we can learn more about Properties of .
to
Link representing the destination route . When clicked , The interior will immediately put to The value of router.push(), So this value can be a string or an object that describes the target location .
<!-- character string -->
<router-link to="home">Home</router-link>
<!-- Render the result -->
<a href="home">Home</a>
<!-- Use v-bind Of JS expression -->
<router-link v-bind:to="'home'">Home</router-link>
<!-- Don't write v-bind It's fine too , Just like binding other properties -->
<router-link :to="'home'">Home</router-link>
<!-- ditto -->
<router-link :to="{ path: 'home' }">Home</router-link>
<!-- Named route -->
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
<!-- With query parameters , The following result is /register?plan=private -->
<router-link :to="{ path: 'register', query: { plan: 'private' }}">Register</router-link>
Copy code
replace
Set up replace Attribute words , When clicked , Would call router.replace() instead of router.push(), Navigation doesn't leave history Record .
<router-link :to="{ path: '/abc'}" replace></router-link>
Copy code
append
Set up append After attribute , At the current ( relative ) Add its path before the path . for example , We from /a Navigate to a relative path b, If not configured append, The path is /b, If it's with , Then for /a/b
<router-link :to="{ path: 'relative/path'}" append></router-link>
Copy code
tag
Sometimes I want to <router-link>
Render as some kind of label , for example <li>
. So we use tag
prop Class specifies what label , It also monitors clicks , Trigger navigation .
<router-link to="/foo" tag="li">foo</router-link>
<!-- Render the result -->
<li>foo</li>
Copy code
active-class
Set up Link activation using CSS Class name . It can be replaced by the following code .
<style>
._active{
background-color : red;
}
</style>
<p>
<router-link v-bind:to = "{ path: '/route1'}" active-class = "_active">Router Link 1</router-link>
<router-link v-bind:to = "{ path: '/route2'}" tag = "span">Router Link 2</router-link>
</p>
Copy code
Note that there class Use active-class="_active".
exact-active-class
Configure what should be activated when the link is precisely matched class. It can be replaced by the following code .
<p>
<router-link v-bind:to = "{ path: '/route1'}" exact-active-class = "_active">Router Link 1</router-link>
<router-link v-bind:to = "{ path: '/route2'}" tag = "span">Router Link 2</router-link>
</p>
Copy code
event
Declare events that can be used to trigger navigation . It can be a string or an array of strings .
<router-link v-bind:to = "{ path: '/route1'}" event = "mouseover">Router Link 1</router-link>
Copy code
The above code sets event by mouseover , And move the mouse to Router Link 1 It's on the navigation HTML The content will change .
Share ends today ------------------------------------
copyright notice
author[Front end sophomore],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827093925446l.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- JQuery operation select (value, setting, selected)
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- [vue3] encapsulate custom global plug-ins
- Error using swiper plug-in in Vue
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
guess what you like
-
Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
-
He was cheated by Wang Xiaofei and Li Chengxuan successively. Is an Yixuan a blessed daughter and not a blessed home?
-
Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
-
Pink is Wangyuan online! Back to the peak! The new hairstyle is creamy and sassy
-
Front end interview daily 3 + 1 - day 858
-
Spring Webflux tutorial: how to build reactive web applications
-
[golang] walk into go language lesson 24 TCP high-level operation
-
August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
Random recommended
- Anti Mafia storm: He Yun's helpless son, Sun Xing, is destined to be caught by his dry son
- Introduction to flex flexible layout in CSS -- learning notes
- CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
- Today, let's talk about the arrow function of ES6
- Some thoughts on small program development
- Talk about mobile terminal adaptation
- Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
- JS function scope, closure, let, const
- Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
- Unveil the mystery of ascension
- Asynchronous solution async await
- Analysis and expansion of Vue infinite scroll source code
- Compression webpack plugin first screen loading optimization
- Specific usage of vue3 video play plug-in
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- [25] typescript
- CSS transform Complete Guide (Second Edition) flight.archives 007
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- Decorator pattern of JavaScript Design Pattern
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich