Vue + element-ui + TS package global search component

This article describes how to use element-ui and TypeScript to encapsulate a global search component in a Vue project.

Dependency installation

First you need to install Vue, element-ui and TypeScript dependencies:

npm install vue element-ui --save
npm install typescript ts-loader --save-dev

Component packaging

The global search component is a universal search box that can be used throughout the application. We can use Vue's global components to achieve this functionality.

Create components

First, we need to create a SearchBox.vue file in the src/components directory to encapsulate the search box component.

<template>
  <el-input v-model="keyword" placeholder="请输入关键字" @keyup.enter.native="handleSearch"></el-input>
</template>

<script lang="ts">
import {
    
     Component, Vue } from 'vue-property-decorator';

@Component
export default class SearchBox extends Vue {
    
    
  keyword: string = '';

  handleSearch() {
    
    
    this.$emit('search', this.keyword);
  }
}
</script>

In this component, we use the Input component of element-ui to implement the search box, and realize the two-way binding through the v-model directive. At the same time, we call the handleSearch method in the keyup.enter event to trigger the search operation.

register component

Next, we need to register this component in the main.ts file so that it can be used globally.

import Vue from 'vue';
import SearchBox from './components/SearchBox.vue';

Vue.component('SearchBox', SearchBox);

use components

Finally, we can use this component anywhere we need a search box.

<template>
  <div>
    <search-box @search="handleSearch"></search-box>
    <!-- 其他内容 -->
  </div>
</template>

<script lang="ts">
import {
    
     Component, Vue } from 'vue-property-decorator';

@Component
export default class MyComponent extends Vue {
    
    
  handleSearch(keyword: string) {
    
    
    // 处理搜索请求
  }
}
</script>

In this example, we use the SearchBox component in the MyComponent component and handle the search request through the @search event.

Summarize

Through the above steps, we successfully encapsulated a global search component and used it in the Vue project. Using TypeScript can make our code more robust and maintainable.

Guess you like

Origin blog.csdn.net/qq_27244301/article/details/131510203