Home  >  Article  >  Web Front-end  >  Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

藏色散人
藏色散人forward
2023-01-13 16:22:213213browse

This article brings you relevant knowledge about Vue3. It mainly introduces how Vue3 implements a global search box. I will share my complete implementation ideas. Let’s take a look. Hope it helps those in need.

How to implement a global search box in Vue3

Preface: Since learning vue, I have been thinking about the global command K function of the vue official website to call up the global keyword search function. It just so happens that a recent project also needs to implement a global search function, and it just so happens that I can learn the idea of ​​​​this function with pay. The level of tutorials on the Internet is uneven, and in a previous project, I happened to have done a function similar to global pop-up breadcrumbs, so I drew inferences and wrote a global search box that our project needs, and I would like to share my ideas.

Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

Note: This article will not teach you how to write code right away, but will serve as a guide to guide you step by step to understand the design of this component. ideas. Will explain it from the perspective of "If I am a beginner, if someone can tell me this when I am learning this knowledge, then I can understand it quickly" Professor It is better to teach people how to fish than to teach them how to fish. I hope you can expand your thinking and draw inferences when reading this article. 1. File preparation

You need to prepare three files in the early stage to complete this global search box

  • SearchBar.ts

    File

  • SearchBar.vue

    File

  • useSearch.ts

    File

Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)2. Search box style

Style issues are not the focus of this article, you can spend five minutes on

SearchBar.vue

Sketch a very simple square div in the file and wrap it with an input tag to quickly proceed with the following learning. But first we need to clarify our thinking. This component will appear at the top of our page, so absolute layout needs to be used inside the component. Let’s go to

SearchBar.vue

to set a style for the outermost div. The other styles here are written using Uno CSS, which is small and unused. Friends don’t need to worry, it’s just a simple style and has nothing to do with the central content of this article. (CSS written as computed properties has no special meaning in this scenario, it is just more consideration during design) Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)3. Rendering function

h

andrender Function (Key Point)

    Open the
  • SearchBar.ts

    file prepared previously and import these two from vue function, and introduce the simple version of the search box (SearchBar.vue) written in the previous step into this file. Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

  • Readers who have read my previous article
  • Vue3 implements a Toast

    may be a little more familiar with it, but in that article, it was also my first time I came into contact with these two functions, so the summary at that time was not particularly accurate, so I reorganized my thinking and explain it here.

  • First of all, let’s take a look at the definition of this function from the introduction on the official website.
  • It can be seen that the first parameter of this function is required and can be a Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)string
    and Component. This article focuses on the parameters The case of Component. The point is that the return value of this function is a VNode, which you must be familiar with, Virtual Node. Readers of this article may be familiar with virtual dom The principle may not be so clear, but I believe you must know its basic mechanism. Vue actually renders virtual dom first -->and then converts it into real dom.

  • Don’t rush to write the code. I think you may know this way of writing better, such as the simple pop-up box we wrote in the SearchBar.vue file earlier. Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)The style of the entire component is written in the component provided by Vue, but you have to know that Vue still passes Call h() to complete the construction of the virtual dom. And is just syntactic sugar provided by Vue to allow you to develop with the familiar native html. (Well, you can understand it this way)

  • Then we can according to the introduction of the h() function above, the first parameter it receives can be Component , then isn’t our SearchBar.vue just a component? So if I don’t want to use to display this component, can I write it like this? h(SearchBar.vue). Yes, yes, you can write it like this. Don’t forget that the return value of h is the Vnode we want to get, so the correct way to write it is like this. Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

##3. Write

SearchBarMaker constructor and present method

  • Let’s Go back to the

    SearchBar.ts file. Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

  • First think about it, this search box must have a function that appears and a function that disappears?, ok, give a name, one

    present, one dismiss .
    Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

  • Next I need to create a

    VNode and then find a way to process it into a real dom. After the above study, you can immediately think of the following writing method in the first step.
    Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

  • #The following one is even more important,

    render() function. Now that we have virtual dom, how can we get real dom? Vue provides us with such a function. Here we need to focus on seeing that the type of this function is a value, which is a RootRenderFunction type. Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

  • Here we change our thinking and look at the second parameter of the

    render function is a container:HostElement, and then Let's open our main.ts file, let's jump into the definition part of mount, Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)Did you find the magic place, although we don't know Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)HostElement What is the type of , but do you know what parameters are filled in your mount function? (If I forgot, I turned around and consciously reviewed the official website.) Yes, it is the only real
    dom in the world, a simple div# with the ID name app ## element. Due to space limitations, you can briefly understand here first. The renderDetailed graphic explanation of the steps to implement the global search box in Vue3 (with code) function will wrap your virtual dom into a real dom element. But you need to give it a real shell dom to tell it where to render the virtual dom.

  • ok, after getting a packaged virtual dom, the next step is to tell the browser where to render this element. What we need to think about here is that since it can pop up globally, it needs to pop up on all components. Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)The simplest way is to make it appear in the first element of body, then it will be at the same level as all the components of our web page (tips: usually all our page components will be written in body internal is within a div. What? You ask me why? Please open your index.html and take a look. Have you forgotten our App.vue is hung in this real element with id app)Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)In fact, the idea of ​​​​our operation is very simple. When I press the global search button , then you can insert my component before the element of <div id="app">. <img src="https://img.php.cn/upload/article/000/000/020/659e9d144b30400682dc69d8bf2b853c-18.png" alt="Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)" loading="lazy"><li><p>Okay, now we can see the basic effect, let’s test it. Let us write a button in the <code>App.vue component, and then call the present method on the SearchBarCreator instance. (maker doesn’t feel so reasonable. Later we changed SearchBarMaker to SeachBarCreator. Only the name changed, and the logic didn’t change at all. .?)Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)The effect is as follows:
    Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

  • HeresearchBar can be rendered on the page, but we don’t know how yet Making it disappear is actually very simple. We just need to remove this dom element at the right time. Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)We need to know one thing here, we need to promote searchBar to the global scope of the current file, not just new in open.
    Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)ok, let’s test it
    Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

  • 4. Optimize the code logic of the SearchBarCreator constructor

    When I write this, You may have discovered a small problem. When I keep pressing the Search button, multiple search boxes will appear, but what we hope is that only one search box will appear globally. Thinking about it from another angle, that is, at the same time, only one instance of this SeachBar created by us new can appear. Think about it?, I add a variable, isShowing is being displayed, if it is being displayed, then when the user calls present again, I will call the instance itselfdismiss Is it feasible to make it disappear?
    Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)Test it:
    Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)
    OK, it seems that the current problem is perfectly solved.

    5. Write a globally unique calling instance

    • In the above case, we can already go in the App.vue file new An example to call this search box. But what if we add that we now need to call this search box in the XXX.vue file? Do I still need to re-introduce it and then new? nonono, a certain boss said that programmers are very lazy and cannot write such low-level repetitive code. So how to achieve it

    • Open the useSearch.ts file we prepared before, and we transform the SearchBar instance that was previously generated globally in App.vue to make it Generate one in a global ts file, and then encapsulate some of the methods of this instance itself into functions and expose them to the outside. Then I can call these two methods on this instance anywhere in the world. Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

    • Let’s try it out in App.vue.
      This is the calling method of our previous App.vue file. Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)Let’s transform it. Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)Let’s test the function again to see if there are any problemsDetailed graphic explanation of the steps to implement the global search box in Vue3 (with code)
      This will be much more convenient. We can call this “only search box” at any location

    6. Add global shortcut keysCommand K

    • Before doing this, we need to understand a concept and pay attention to our main.ts File, who did we hang under the real dom of the global id='app'? Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)
      Yes, it is the App.vue component we mentioned earlier.

    • So if I add a keyboard event to the global window object when this App.vue component is mounted, right? Is that enough? How to add it? In fact, it is very, very simple. To use the key combination, we need to use "keydown". Why is it not "keypress"? Readers can check the difference between the two by themselves. It is not the main content of this article. Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

    • At this time, let’s click command to see what is printed. The focus here is the metaKey attribute on the keyboard event. Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)Here we can also deduce that the event of pressing "ctrl" is Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

    • keydown events support multiple The keys are pressed simultaneously. What happens when we press the "command" and "K" keys at the same time? Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)But we found that there does not seem to be the attribute K:true, so how can we judge? Don't worry and continue looking down.

    • We can see that the keyboard event event has a key attribute, and its value happens to be a string type " k”,Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)


    Here I will directly publish the writing method. js allows us to judge whether two buttons are pressed at the same time. Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

    • Let’s test it, let’s go App.vue Remove these two buttons in the fileDetailed graphic explanation of the steps to implement the global search box in Vue3 (with code) Then print it and press it command and k when. Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)Test it:Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

    7. Add the animation that appears

    • As we can see above, such a sudden appearance There seems to be a little bit of abruptness. I hope that this search box can have a slight panning effect when it appears. (Similar to the effect below) How can I do this? ?Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

    • I will introduce a simpler idea here. We preset a Css in the style of the App.vue file. Animation and give it a good name. Called "searchInput"Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

    • Then go back to our searBar.vue component and give us the outermost layer of this component Give it a nice name, I’ll call it searchBarWrapper. Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

    • Then go back to our SearchBar.ts file, which is the file where our SeachBarCreator constructor is placed. (tips: Not useSearch.ts) Let me explain the idea here. After calling the render function, this component has actually been rendered into a real dom element, but we have not specified the rendering position for it. Since it is a real dom, then we can get this SearchBar.vue component through the document.getElementById method (the same as querySelector, the same meaning), Next, I only need to add the class name we just preset in App.vue before calling the document.body.insertBefore method, searchInput , the effect we want is perfectly achieved. Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

    • Note: style, this point is just a class name selector, don’t forget the basics. Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

    • Test the effect: Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

    8. Automatically focus

    on the ## of the pop-up box #input Implementing auto-focusing on the frame is very simple compared to what was mentioned before. I have just gone through it here. Just call the focus method of input itself in nextTick.
    Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

    Summary:

    The reason why I don’t like to use real code to write articles but use a lot of screenshots is: after I search for the article I want, They also like to directly see if there is any final product code, and then directly copy it and use it, but often ignore the process of truly understanding it by implementing it by yourself.

    So when I write code, I try not to write particularly complex logic, but write some very simple lines of code to implement a certain function. Because I hope you can really bring your own thinking and experience the implementation process step by step, so as to draw inferences from one example.

    If you read the article carefully, you may understand that the underlying implementation principles of many component libraries are actually like this, such as the global pop-up

    dialog, modal box etc. We need to understand the idea of ​​component library component implementation, rather than just copy and paste.

    There are many areas where this search box can be optimized, and you can bring your own thoughts into it. For example

    1. How to save search history?
    2. How to provide real-time search associations

    My original intention is to encourage you...

    Source code

    The core code is posted here

    SearchBar.ts The source code of the file is posted. I hope readers can use it as a reference only and do not want to copy and paste it directly.

    import { h, render } from "vue"
    
    import SearchBar from "./SearchBar.vue"
    class SearchBarCreator {
      container: HTMLElement
      appElement: HTMLElement | null
      showing: boolean
      _dismiss: () => void
      constructor() {
        this.container = document.createElement("div")
        this.showing = false
        this.appElement = document.body.querySelector("#app")
        this.present.bind(this)
        this.dismiss.bind(this)
        this._dismiss = this.dismiss.bind(this)
      }
    
      present() {
        if (this.showing) {
          this.dismiss()
        } else {
          const SearchBar = h(h(SearchBar))
          render(SearchBar, this.container)
          const searchBarWrapperDOM =
            this.container.querySelector("#searchBarWrapper")
          searchBarWrapperDOM?.classList.add("animate-searchInputAnimation")
          document.body.insertBefore(this.container, document.body.firstChild)
          this.showing = true
          this.appElement?.addEventListener("click", this._dismiss)
        }
      }
    
      dismiss() {
        if (this.showing && this.container) {
          render(null, this.container)
          document.body.removeChild(this.container)
          this.showing = false
          this.appElement?.removeEventListener("click", this._dismiss)
        } else {
          console.log("不需要关闭")
        }
      }
    }

    Recommended learning: "

    vue.js Video Tutorial"

The above is the detailed content of Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete
Previous article:Analyze the principle of Vue2 implementing composition APINext article:Analyze the principle of Vue2 implementing composition API

Related articles

See more