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:21 3128browse

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 globalcommand Kfunction 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 squaredivin the file and wrap it with aninputtag 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 outermostdiv. The other styles here are written usingUno 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

andrenderFunction (Key Point)

    Open the
  • SearchBar.ts

    file prepared previously and import these two fromvuefunction, 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 aDetailed graphic explanation of the steps to implement the global search box in Vue3 (with code)string
    andComponent. This article focuses on the parametersThe case of Component. The point is that the return value of this function is aVNode, which you must be familiar with,Virtual Node. Readers of this article may be familiar with virtualdomThe principle may not be so clear, but I believe you must know its basic mechanism.Vueactually rendersvirtual 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 theSearchBar.vuefile 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 byVue, but you have to know thatVuestill passes Callh()to complete the construction of the virtualdom. And is just syntactic sugar provided byVueto allow you to develop with the familiar nativehtml. (Well, you can understand it this way)

  • Then we can according to the introduction of theh()function above, the first parameter it receives can beComponent, then isn’t ourSearchBar.vuejust 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 ofhis theVnodewe 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

SearchBarMakerconstructor andpresentmethod

  • Let’s Go back to the

    SearchBar.tsfile.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, onedismiss.
    Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

  • Next I need to create a

    VNodeand then find a way to process it into a realdom. 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 virtualdom, how can we getreal dom?Vueprovides us with such a function. Here we need to focus on seeing that the type of this function is a value, which is aRootRenderFunctiontype.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

    renderfunction is acontainer:HostElement, and then Let's open ourmain.tsfile, let's jump into the definition part ofmount,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 knowDetailed 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 yourmountfunction? (If I forgot, I turned around and consciously reviewed the official website.)Yes, it is the only real
    domin the world, a simplediv# with the ID nameapp## element.Due to space limitations, you can briefly understand here first. TherenderDetailed graphic explanation of the steps to implement the global search box in Vue3 (with code)function will wrap your virtualdominto a realdomelement. But you need to give it a realshell domto tell it where to render the virtualdom.

  • 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 ofbody, 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 inbody internalis within adiv. What? You ask me why? Please open yourindex.htmland take a look. Have you forgotten ourApp.vueis hung in this real element withid 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

    . Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)
  • Okay, now we can see the basic effect, let’s test it. Let us write a button in the App.vuecomponent, and then call thepresentmethod on theSearchBarCreatorinstance. (makerdoesn’t feel so reasonable. Later we changedSearchBarMakertoSeachBarCreator. 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)

  • HeresearchBarcan be rendered on the page, but we don’t know how yet Making it disappear is actually very simple. We just need to remove thisdomelement 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 promotesearchBarto the global scope of the current file, not justnewinopen.
    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 theSearch 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 thisSeachBarcreated by usnewcan appear. Think about it?, I add a variable,isShowing is being displayed, if it is being displayed, then when the user callspresentagain, I will call the instance itselfdismissIs 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 theApp.vuefilenewAn example to call this search box. But what if we add that we now need to call this search box in theXXX.vuefile? Do I still need to re-introduce it and thennew? nonono, a certain boss said that programmers are very lazy and cannot write such low-level repetitive code. So how to achieve it

    • Open theuseSearch.tsfile we prepared before, and we transform the SearchBar instance that was previously generated globally inApp.vueto make it Generate one in a globaltsfile, 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 inApp.vue.
      This is the calling method of our previousApp.vuefile.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 ourmain.tsFile, who did we hang under the realdomof the globalid='app'?Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)
      Yes, it is theApp.vuecomponent we mentioned earlier.

    • So if I add a keyboard event to the globalwindowobject when thisApp.vuecomponent 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 clickcommandto see what is printed. The focus here is themetaKeyattribute 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"isDetailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

    • keydownevents 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 attributeK:true, so how can we judge? Don't worry and continue looking down.

    • We can see that the keyboard eventeventhas akeyattribute, 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 goApp.vueRemove 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 itcommandandkwhen.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 aCssin thestyleof theApp.vuefile. 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 oursearBar.vuecomponent and give us the outermost layer of this component Give it a nice name, I’ll call itsearchBarWrapper.Detailed graphic explanation of the steps to implement the global search box in Vue3 (with code)

    • Then go back to ourSearchBar.tsfile, which is the file where ourSeachBarCreatorconstructor is placed. (tips: NotuseSearch.ts) Let me explain the idea here. After calling therenderfunction, this component has actually been rendered into a realdomelement, but we have not specified the rendering position for it. Since it is a realdom, then we can get thisSearchBar.vue componentthrough thedocument.getElementById method (the same as querySelector, the same meaning), Next, I only need to add the class name we just preset inApp.vuebefore calling thedocument.body.insertBeforemethod,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 #inputImplementing auto-focusing on the frame is very simple compared to what was mentioned before. I have just gone through it here. Just call thefocusmethod ofinputitself innextTick.
    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,modalbox 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.tsThe 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