In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly explains "how to build a complete project structure for Vue3 and TypeScript". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to build a complete project structure for Vue3 and TypeScript.
I. Project construction
It is recommended to build our SPA project in two ways in the Quickstart of the official warehouse:
Vite
Npm init vite-app sail-vue3 # OR yarn create vite-app sail-vue3
Vue-cli
Npm install-g @ vue/cli # OR yarn global add @ vue/clivue create sail-vue3# select vue3 preset
Vite is a Web development and build tool driven by native ESM. Opening the package.json of vite dependency, you can find that TypeScript has been introduced into devDependencies development dependency, and even vuex, vue-router, less, sass and other tools that local developers often need. Vite lightweight, out-of-the-box features, to meet the needs of most development scenarios, as a quick start local Vue project, this is a very perfect tool.
The following demo code is also built with vite.
Diggers from vue2.x must know that vue-cli is the official scaffolding. How can the update of vue3 be less than vue-cli? vue-cli puts more emphasis on interactive configuration in the way of cli, and the choice is more flexible and controllable. Rich official plug-in adaptation, GUI creation management interface, standardized development process, these are the characteristics of vue-cli.
Vue-cli ✖ TypeScript STEP1
Vue-cli ✖ TypeScript STEP2
If you want to pre-install TypeScript, you need to choose manual configuration and check a good TypeScript
It's okay to forget to use TypeScript, just add a line of cli command.
Vue add typescript
Finally, don't forget to add the lang= "ts" to the script tag in the .vue code
II. Option API style
Diggers who have used TypeScript on Vue2.x must know that introducing TypeScript is not an easy task:
To strengthen vue components with vue-class-component, let Script support TypeScript decorator
Use vue-property-decorator to add more decorators that combine Vue features
Introduce ts-loader to let webpack recognize .ts .tsx files
.
Then the style of the code looks like this:
@ Component ({components: {componentA, componentB},}) export default class Parent extends Vue {@ Prop (Number) readonly propellant: number | undefined @ Prop ({default: 'default value'}) readonly propellant: string @ Prop ([String) Boolean]) readonly propellant: string | boolean | undefined / / data information message = 'Vue2 code style' / / calculation attribute private get reversedMessage (): string [] {return this.message.split ('). Reverse (). Join (')} / / method public changeMessage (): void {this.message = 'Good bye'}
Class-style components, a variety of decorators interspersed in the code, a little feel that they are not writing vue, a little messy, so this kind of curve rescue solution will certainly not work in vue3.
You can write this directly in vue3:
Import {defineComponent, PropType} from 'vue'interface Student {name: string class: string age: number} const Component = defineComponent ({props: {success: {type: String}, callback: {type: Function as PropType void >}, student: {type: Object as PropType, required: true}}, data () {return {message:' Vue3 code style'}} Computed: {reversedMessage (): string {return this.message.split ('') .reverse () .join ('')}})
When vue validates the complex type of props, it directly uses PropType to cast, the data returned in data can infer most types when the type is not explicitly defined, and computed only needs to return the calculation properties of the type, the code is clear, the logic is simple, and ensures the integrity of the vue structure.
Third, Composition API style
In vue3's Composition API code style, the typical api is ref and reactive. Let's take a look at how these two make type declarations:
Refimport {defineComponent, ref} from 'vue'const Component = defineComponent ({setup () {const year = ref (2020) const month = ref (' 9') month.value = 9 / / OK const result = year.value.split ('') / / = > Property 'split' does not exist on type' number'}})
Analyzing the above code, we can find that if we do not give the type defined by ref, vue3 can also derive the type based on the initial value, and then simply pass a generic type when you need to specify a complex type.
Tips:
If there is only the setup method, you can pass the setup function directly into the defineComponent
Const Component = defineComponent (() = > {const year = ref (2020) const month = ref ('9') month.value = 9 / / OK const result = year.value.split ('') / / = > Property 'split' does not exist ont ype' number'}) reactiveimport {defineComponent, reactive} from 'vue'interface Student {name: string class?: string age: number} export default defineComponent ({name:' HelloWorld', setup () {const student = reactive ({name: 'Yong') Age: 16}) / / or const student: Student = reactive ({name:'Ah Yong', age: 16}) / / or const student = reactive ({name:'A Yong', age: 16, class: 'cs'}) as Student}})
Interfaces are recommended when declaring reactive, and then there are many options for how to use type assertions. This is the syntax sugar of TypeScript, which is essentially the same.
IV. Custom Hooks
Vue3 uses react hooks for reference to develop Composition API, which means that Composition API can also customize and encapsulate hooks, and then we will encapsulate a counter logic hooks (useCount) in TypeScript style:
First, let's take a look at how to use this hooks:
Import {ref} from'/ @ modules/vue'import useCount from'. / useCount' export default {name: 'CountDemo', props: {msg: String}, setup () {const {current: count, inc, dec, set, reset} = useCount (2, {min: 1, max: 15}) const msg = ref (' Demo useCount') return {count, inc, dec, set, reset Msg}
The effect is:
Paste the source code of useCount:
Import {ref, Ref, watch} from 'vue'interface Range {min?: number, max?: number} interface Result {current: Ref, inc: (delta?: number) = > void, dec: (delta?: number) = > void, set: (value: number) = > void, reset: () = > void} export default function useCount (initialVal: number Range?: Range): Result {const current = ref (initialVal) const inc = (delta?: number): void = > {if (typeof delta = 'number') {current.value + = delta} else {current.value + = 1} const dec = (delta?: number): void = > {if (typeof delta =' number') {current.value-= delta} else {current.value-= 1 }} const set = (value: number): void = > {current.value = value} const reset = () = > {current.value = initialVal} watch (current (newVal: number, oldVal: number) = > {if (newVal = oldVal) return if (range & & range.min & & newVal
< range.min) { current.value = range.min } else if (range && range.max && newVal >Range.max) {current.value = range.max}}) return {current, inc, dec, set, reset}}
Analyze the source code
First of all, the input parameter type and return type of the hooks function are defined. The Range of the input parameter and the Result returned are specified by an API respectively. After doing so, the greatest advantage is that when using the useCount function, ide will automatically prompt which parameters are required and what the type of each parameter is, to prevent business logic errors.
Next, the typeo type guard check is added to the functions that add inc and decrease dec, because the value of the delta type passed in is uncertain in some specific scenarios, for example, if the method is called in template, the type check may fail, and the type passed in is a native Event.
With regard to ref type values, there is no special type declaration here, because vue3 does automatic type inference, but if it is a complex type, you can use type assertion: ref (initObj) as Ref
5. Tips?
AnyScript
In the early days of using TypeScript, many diggers like to use the any type and rigidly write TypeScript as AnyScript. Although it is very convenient to use, it loses the meaning of TypeScript type checking. Of course, the habit of writing types needs to be formed slowly, and there is no need to rush for a while.
Vetur
Vetur code review tools can be very useful when writing vue code, just like building a vue project without vue-cli, vetur provides plug-in support for vscode, so bring vetur along with you in the rush to upgrade vue3.
VI. A complete Vue3+ts project ├─ public │ favicon.ico │ index.html └─ src │ App.vue │ main.ts │ shims-vue.d.ts ├─ assets │ │ logo.png │ └─ css │ base.css │ main.styl ├─ components │ │ HelloWorld.vue └─ base Button.vue │ index.ts │ Select.vue ├─ directive │ focus.ts │ index.ts │ pin.ts ├─ router │ index.ts ├─ store │ index.ts ├─ utils │ │ cookie.ts │ │ deep-clone.ts │ │ Index.ts │ │ storage.ts │ └─ validate │ date.ts │ email.ts │ mobile.ts │ number.ts │ system.ts └─ views │ About.vue │ Home.vue │ LuckDraw.vue │ TodoList.vue └─ address AddressEdit.tsx AddressList.tsx
.vue writing method
... Import dayjs from "dayjs"; import {ref, reactive, onMounted} from "vue"; import {Button, Step, Steps, NoticeBar} from "vant"; export default {components: {Button, Step, Steps, NoticeBar,}, setup () {const nameinput = ref (); const selectionStart = ref (0); const twoNow = dayjs (). Subtract (2, "day"). Format ("YYYY-MM-DD HH:mm:ss") Const now = dayjs (). Format ("YYYY-MM-DD HH:mm:ss"); const now2 = dayjs (). Add (2, "day"). Format ("YYYY-MM-DD HH:mm:ss"); const formData = reactive ({name: ", phone:", code: ",}); onMounted () = > {(nameinput.value as HTMLInputElement) .focus ();}) Const insertName = () = > {const index = (nameinput.value as HTMLInputElement) .selectionStart; if (typeof index! = = "number") return; formData.name = formData.name.slice (0, index) + "" + formData.name.slice (index);}; return {nameinput, formData, insertName, selectionStart, twoNow, now, now2,};},} .. import dayjs from "dayjs"; import {defineComponent} from "vue"; import HelloWorld from "@ / components/HelloWorld.vue"; / / @ is an alias to / srcimport {Button, Dialog, Toast} from "vant" Export default defineComponent ({name: "Home", components: {HelloWorld, Button,}, data () {return {direction: "top", pinPadding: 0, time: "", timer: 0, color: "red",}; methods: {showToast () {Toast ("font color changed blue"); this.color = "blue" }, handleClick () {Dialog ({title: "title", message: "this is a global button component",});}, initTime () {this.time = dayjs () .format ("YYYY-MM-DD HH:mm:ss") This.timer = setInterval (() = > {this.time = dayjs (). Format ("YYYY-MM-DD HH:mm:ss");}, 1000);},}, created () {this.initTime ();}, beforeUnmount () {clearInterval (this.timer);},}); .text-color {color: var (--color);}
Tsx writing method
Import {ref, reactive} from "vue"; import {AddressList, NavBar, Toast, Popup} from "vant" Import AddressEdit from'. / AddressEdit'import router from'@ / router'export default {setup () {const chosenAddressId = ref ('1') const showEdit = ref (false) const list = reactive ([{id: '1Qing, name:' Zhang San', tel: '1300000000000, address: room 501, 7th floor, Dongfang Communication Building, 138Wen San Road, Xihu District, Hangzhou City, Zhejiang Province) IsDefault: true,}, {id: '2Qing, name:' Li Si', tel: '131000000000000, address:' 50 Mogan Mountain Road, Gongshu District, Hangzhou City, Zhejiang Province',},] const disabledList = reactive ([{id: '3Qing, name:' Wang Wu', tel: '1320000000000' Address:'15 Jiangnan Avenue, Binjiang District, Hangzhou City, Zhejiang Province',},] const onAdd = () > {showEdit.value = true} const onEdit = (item: any, index: string) = > {Toast ('Editing address:' + index) } const onClickLeft = () = > {router.back ()} const onClickRight = () = > {router.push ('/ todoList')} return () = > {return ();} Thank you for your reading, the above is the content of "how to build a complete project structure of Vue3 and TypeScript". After the study of this article, I believe you have a deeper understanding of how to build a complete project structure of Vue3 and TypeScript. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.