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 , stay  v-my-directive="1 + 1"  in , The value is  2.
  • oldValue: Previous value , Only in  beforeUpdate  and  updated  Available in the . Whether the value has been changed is available .
  • arg: Parameters are passed to the instruction ( If there is ). For example, in  v-my-directive:foo  in ,arg by  "foo".
  • modifiers: Include modifier ( If there is ) The object of . For example, in  v-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

Random recommended