Vue3 user-defined instruction

In addition to the core directives set by default (V-model and V-show), Vue also allows the registration of custom directives.

We register a global directive, V-focus, that gives the element focus when the page loads:

<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title>Vue test instance </title> <script SRC ="https://unpkg.com/vue@next"></script> </head> <body> <div id="app"> <p> The input element automatically gets focus when the page loads: </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 into the DOM... Mounted (el) {/ / el focusing element. The focus ()}}) app. Mount (' # app) < / script > < / body > < / HTML >Copy the code

We can also use the Directives option in the instance to register local directives so that the directives can only be used in this instance:

<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title>Vue test instance </title> <script SRC ="https://unpkg.com/vue@next"></script> </head> <body> <div id="app"> <p> The input element automatically gets focus when the page loads: </p> <input v-focus> </div> <script> const app = { data() { return { } }, directives: { focus: {/ / instructions define mounted (el) {el. Focus ()}}}} Vue. CreateApp (app). The mount (' # app) < / script > < / body > < / HTML >Copy the code

hook

Hook function

The instruction definition function provides several hook functions (optionally) :

  • created : called before the attribute or event listener of the bound element is applied.
  • beforeMount The: directive first binds to the element and is called before the parent component is mounted.
  • mounted : called after the parent component of the bound element has been mounted.
  • beforeUpdate: called before updating the VNode containing the component.
  • updated: called after the VNode containing the component and its children are updated.
  • beforeUnmount: is called only once when the directive is unbound from an element and the parent component is unmounted.
  • unmounted: is called only once when the directive is unbound from an element and the parent component is unmounted.
Import {createApp} from 'vue' const app = createApp({}) // Register app.directive('my-directive', {// Directives have a set of lifecycle hooks: Create () {} is called before the attribute or event listener of the bound element is applied. BeforeMount () {} is called before the parent of the bound element is mounted. Mounted () {} is called when the parent of the bound element is mounted. Call beforeUpdate() {} before the VNode containing the component is updated, // Call updated() {} after the VNode containing the component and its children are updated, Call beforeUnmount() {} before unmounting the parent of a bound element, call unmounted() {}} when unmounting the parent of a bound element. Const myDirective = app.directive('my-directive') const myDirective = app.directive('my-directive')Copy the code

Hook function arguments

The hook function takes the following arguments:

el

The element to which the el directive is bound. This can be used to manipulate the DOM directly.

binding

Binding is an object containing the following attributes:

  • instance: component instance that uses the directive.
  • value: The value passed to the instruction. For example, in thev-my-directive="1 + 1", the value is2.
  • oldValue: Previous value, only inbeforeUpdate 和 updatedAvailable in. Whether or not the value has changed is available.
  • argThe: argument is passed to the instruction (if any). For example, inv-my-directive:fooThe arg is"foo".
  • modifiers: An object containing modifiers (if any). For example, inv-my-directive.foo.bar, the modifier object is{foo: true, bar: true}.
  • dir: an object passed as a parameter when a directive is registered. For example, in the following directive:
app.directive('focus', {
  mounted(el) {
    el.focus()
  }
})
Copy the code

Dir will be the following object:

{
  mounted(el) {
    el.focus()
  }
}
Copy the code

vnode

Blueprints of real DOM elements received as el parameters.

prevNode

Last virtual node, available only in beforeUpdate and Updated hooks.

The following example demonstrates the use of these parameters:

<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title>Vue test instance </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 the code

Sometimes we don’t need any other hook functions, we can abbreviate the function as follows:

Directive ('runoob', function (el, binding) {// set the backgroundColor of the directive el.style.backgroundcolor = binding.value.color})Copy the code

The directive function accepts all valid JavaScript expressions, and the following instances pass in JavaScript objects:

<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title>Vue test instance </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 the code

Vue3 routing

Vue routing allows us to access different content through different urls.

Vue enables multi-view single Page Web Application (SPA).

Vue.js routes need to be loaded into vue-Router library

English document address: vue-router document

The installation

1, direct download/CDN

https://unpkg.com/vue-router@4
Copy the code

NPM

Recommended use of Taobao mirror:

npm install -g cnpm --registry=https://registry.npm.taobao.org
cnpm install vue-router@4
Copy the code

Simple example

Vue. Js + Vue – Router can easily implement a single page application.


is a component that sets up a navigation link to switch between different HTML content. The to attribute is the target address, which is the content to display.

In the following example we add vue-Router, configure the component and route mapping, and tell vue-Router where to render them. The code looks like this:

HTML code: <script src="https://unpkg.com/vue@3"></script> <script src="https://unpkg.com/vue-router@4"></script> <div id="app"> <h1>Hello App! </h1> <p> <! -- Use the router-link component for navigation --> <! -- Specify links by passing 'to' --> <! -- '<router-link>' will render a '<a>' tag with the correct 'href' attribute --> <router-link to="/">Go to Home</router-link> <router-link to="/about">Go to About</router-link> </p> <! -- Routing exit --> <! <router-view></router-view> </div>Copy the code

router-link

Note that instead of using the regular A tag, we used a custom component, router-link, to create the link. This allows the Vue Router to change urls, handle URL generation, and encoding without reloading the page. We’ll see how you can benefit from these features later.

router-view

Router-view displays the component corresponding to the URL. You can put it anywhere to fit your layout.

JavaScript code: <! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title>Vue test instance </title> <script src="https://unpkg.com/vue@next"></script> <script src="https://unpkg.com/vue-router@4"></script> </head> <body> <div id="app"> <h1>Hello App! </h1> <p> <! -- Use the router-link component for navigation --> <! -- Specify links by passing 'to' --> <! -- '<router-link>' will render a '<a>' tag with the correct 'href' attribute --> <router-link to="/">Go to Home</router-link> <router-link to="/about">Go to About</router-link> </p> <! -- Routing exit --> <! <router-view></router-view> </div> <script> // 1. // You can also import const Home = {template: '<div>Home</div>'} const About = {template: '<div>About</div>'} // 2. Define some routes // Each route needs to map to a component. // We will discuss nested routines later. const routes = [ { path: '/', component: Home }, { path: '/about', component: About }, ] // 3. Const router = VueRouter. CreateRouter ({// 4. An implementation of the History pattern is provided internally. For simplicity, we use hash mode here. History: VueRouter createWebHashHistory (), routes, / / ` routes: routes ` abbreviations}) / / 5. Create and mount the root instance const app = vue.createApp ({}) // Make sure the _use_ routing instance enables // the entire application to support routing. App.use (router) app.mount('#app') </script> </body> </html>Copy the code

All clicked navigation links are styled with class =”router-link-exact-active router-link-active”.

Relevant properties

Next we can learn more about the properties of.

to

Represents a link to the destination route. When clicked, the internal value of to is immediately passed to router.push(), so this value can be a string or an object describing the destination location.

<! - string - > < the router - link to = "home" > home < / router - the link > <! <a href="home"> home </a> <! <router-link V-bind :to="'home' > home </router-link> <! <router-link :to="'home' > home </router-link> <! -- -- ditto -- -- > < the router - link: to = "{path: 'home'}" > home < / router - the link > <! --> <router-link :to="{name: 'user', params: {userId: 123}}"> user </router-link> <! /register? plan=private --> <router-link :to="{ path: 'register', query: { plan: 'private' }}">Register</router-link>Copy the code

replace

With the replace attribute, when clicked, router.replace() is called instead of router.push(), and no history is left after navigation.

<router-link :to="{ path: '/abc'}" replace></router-link>
Copy the code

append

After the AppEnd property is set, its path is added before the current (relative) path. For example, if we navigate from /a to a relative path B, the path is /b if append is not configured, and /a/b if configured

<router-link :to="{ path: 'relative/path'}" append></router-link>
Copy the code

tag

Sometimes you want

to be rendered as some kind of tag, such as

  • . So we use the Tag Prop class to specify which tag, which again listens for clicks and triggers navigation.
  • <router-link to="/foo" tag="li">foo</router-link> <! Render result --> <li>foo</li>Copy the code

    active-class

    Sets the name of the CSS class to use when the link is activated. You can use the following code instead.

    <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 the code

    Note that active-class=”_active” is used here.

    exact-active-class

    Configures the class that should be activated when a link is exactly matched. You can use the following code instead.

    <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 the code

    event

    Declares events that can be used to trigger navigation. It can be a string or an array containing strings.

    <router-link v-bind:to = "{ path: '/route1'}" event = "mouseover">Router Link 1</router-link>
    Copy the code

    The above code sets the event to Mouseover, and the HTML content of the navigation changes when the mouse moves over Router Link 1.

    End of today’s share ————————————