Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use vue3+TS to realize simple component Library

2025-04-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you "how to use vue3+TS to achieve a simple component library", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to use vue3+TS to achieve a simple component library" this article.

Front position

First download vue-cli, build our environment, vue-create-luckyUi, and select vue3 and TypeScript. Create package as the component directory under the src directory. Then install bootstrap and use the styles in bootstrap to complete our components.

Component programming dropdown

First look at the boorstrap document, which is used in this way

Dropdown button Action Another action Something else here

First of all, the button button is the content of our dropdown button, and this part is passed in as an attribute, while the content of dropdown-menu is as a dropdown-item. Obviously, you can't always write three here, so you can use the slot to occupy the space, and then encapsulate a dropdown-item component.

First of all, the dropdown component is as follows:

{{title}}

The content of dropdown-item is:

Import {defineComponent} from 'vue'export default defineComponent ({name: "DropdownItem", props: {disabled: {type: Boolean, default: false}). Dropdown-option.is-disabled * {color: # 6c757d; pointer-events: none; background-color: transparent;}

Also achieve a click dropdown,dropdown-item will be put away with the function, which is relatively simple, bind a click event on dropdown to control the variable isOpen to true or false, add v-if to achieve the function. The next step is to implement a dropdown-item contraction that can also be achieved elsewhere on the page. Here are two ideas:

First, add a click event to document, set isOpen to false once triggered, add a click event to dropdown, and add an event modifier stop to prevent the event from bubbling, so that document will trigger a click event except anywhere unexpected to click dropdown.

The second idea is to let the event bubble to document, by determining whether the event object includes our target object, and if it does not include a description that you clicked elsewhere on the page, set isOpen to false. The combinatorial api is used here to create a new file package/hooks/useClickOutside.ts

Import {ref, onMounted, onUnmounted, Ref} from 'vue'const useClickOutside = (elementRef: Ref) = > {const isClickOutside = ref (false) const handler = (e: MouseEvent) = > {if (elementRef.value) {if (elementRef.value.contains (e.target as HTMLElement)) {isClickOutside.value = false} else {isClickOutside.value = true}} onMounted (() = > {document.addEventListener (' click') Handler)}) onUnmounted (() = > {document.removeEventListener ('click', handler)}) return isClickOutside} export default useClickOutside

You can then use the defined useClickOutside function by directly importing it. Here you listen to the state of isClickOutside to change the state of isOpen.

Import useClickOutside from ".. / hooks/useClickOutside";... const isClickOutside = useClickOutside (dropdownRef); watch (isClickOutside, () = > {if (isOpen.value & & isClickOutside.value) {isOpen.value = false;}}); form

First of all, take a look at the document usage.

Email address We'll never share your email with anyone else. Password Check me out Submit

First write the ValidateForm component:

Submit import {defineComponent, onUnmounted} from 'vue'import mitt from' mitt'type ValidateFunc = () = > booleanexport const emitter = mitt () export default defineComponent ({emits: ['form-submit'], setup (props, context) {let funcArr: ValidateFunc [] = [] const submitForm = () = > {const result = funcArr.map (func = > func ()) .every (result = > result) context.emit (' form-submit') Result)} const callback = (func?: ValidateFunc) = > {if (func) {funcArr.push (func)}} emitter.on ('form-item-created', callback) onUnmounted () = > {emitter.off (' form-item-created', callback) funcArr = []}) return {submitForm}})

Then write the ValidateInput.vue component:

Import {{inputRef.message}} import {defineComponent, reactive, PropType, onMounted, computed} from 'vue'import {emitter} from'. / ValidateForm.vue'const emailReg = / ^ [a-zA-Z0-9.percent license percent license]? ^ _ `{|} ~ -] + @ [a-zA-Z0-9 -] + (?:\. [a-zA-Z0-9 -] +) * $/ interface RuleProp {type: 'required' |' email' | 'custom'; message: string Validator?: () = > boolean } export type RulesProp = RuleProp [] export type TagType = 'input'export default defineComponent ({props: {rules: Array as PropType, modelValue: String, tag: {type: String as PropType, default:' input'}}, inheritAttrs: false, setup (props, context) {const inputRef = reactive ({val: computed ({get: () = > props.modelValue | |'' Set: val = > {context.emit ('update:modelValue', val)}}), error: false Message:''}) const validateInput = () = > {if (props.rules) {const allPassed = props.rules.every (rule = > {let passed = true inputRef.message = rule.message switch (rule.type) {case 'required': passed = (inputRef.val.trim ()! = ='')) Break case 'email': passed = emailReg.test (inputRef.val) break case' custom': passed = rule.validator? Rule.validator (): true break default: break} return passed}) inputRef.error =! allPassed return allPassed} return true} onMounted (() = > {emitter.emit ('form-item-created', validateInput)}) return {inputRef, validateInput})

There are two points at the core here:

Custom component implementation v-mdel must bind a value property and an input event to pass the input value to value in the input event. In vue3, you need to bind a modelValue and update:modelValue event

There is also the problem of passing values between parent and child components. Because there are slots, there is no way to use regular attributes to pass values. The event values used here use a third-party library, mitt. Events are registered through emitter.on ('form-item-created', callback) in the parent component and triggered by emitter.emit (' form-item-created', validateInput) in the child component.

Verification

Create a new file package/index.ts

Import 'bootstrap/dist/css/bootstrap.min.css'// import component import Dropdown from ". / Dropdown/Dropdown.vue"; import DropdownItem from ". / Dropdown/DropdownItem.vue"; const components = [Dropdown, DropdownItem] const install = (Vue: any) = > {components.forEach ((_: any) = > {Vue.component (_ .name, _);});}; export default {install}

Import the written components in turn, and then define an install function, which has a parameter of the Vue instance, traverses our array of imported components in turn in the function, then mounts the components to the vue instance, and exports the install function.

Use our new component on main.ts in the root directory:

Import {createApp} from 'vue'import App from'. / App.vue'import luckyUi from'. / package/index';const app = createApp (App) app.use (luckyUi); app.mount ('# app')

Test in app.vue:

Wang Da Wang er Wang San Wang Si

Finally, use the scaffolding that comes with vue to pack, you can see the document for details.

Configure the packaging command in package:

"lib": "vue-cli-service build-target lib-name lucky-ui. / src/package/index.ts"

Run npm run lib to view it in the dist directory.

The above is all the contents of the article "how to use vue3+TS to implement a simple component Library". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report