Vue3 + setup + ts 使用总结

news2024/9/20 19:44:17

在这里插入图片描述

阅读vue的英文官网

中文的vue官网比vue的英文官网差很多,这个其实很容易理解,毕竟vue是服务于全球的开源项目之一。

所以程序员的第一生产力还是英语

不管学什么都要去获取第一手资料,不要看中文官网,直接去看英文官网

vite初始化项目

1、pnpm create vite
在这里插入图片描述
2、选择vue,再选择typescript
3、启动项目

  cd test1
  pnpm install
  pnpm run dev

vscode的vue代码片段

根据自己的使用习惯,设置vscode的vue代码片段,推荐使用snippet-generator.app

"vue3模版": {

"prefix": "vue3",

"body": [

   "<template>",

       " <div class='${1:box}'></div>",

   "</template>",

   " ",

   "<script setup lang='ts'>",

   " import {ref,reactive} from \"vue\";",

   " ${3}",

   "</script>",

   " ",

   "<style lang=\"scss\" scoped>",

   " .${2:box} {",

   " }",

   "</style>"

],

"description": "vue3模版"

}

另外vscode的不仅可以设置vue的代码片段,理论上你在vscode上写的任何代码,都可以设置成代码片段,方便自己以后使用。

这个自己根据自己的个人习惯,自己挖掘。

另外因为使用vscode开发vue的typescript项目,vscode还需要安装对应的插件,比如TypeScript Vue Plugin

在这里插入图片描述

3. 组件引入

当使用setup的时候,组件直接引入就可以了,不需要再自己手动注册

4. ref和reactive

ref一般用于基本的数据类型,比如string,boolean
reactive一般用于对象
使用reactive的注意事项:

1、reactive不能用于string,number,boolean
vue官方网站说明如下:It cannot hold primitive types such as string, number or boolean
2、不能修改reactive设置的值
比如:

let state = reactive({ count: 0 }) 
// the above reference ({ count: 0 }) is no longer being tracked (reactivity connection // is lost!) 
// 这里state如果重新赋值以后,vue就不能双向绑定
state = reactive({ count: 1 })

ref的底层实现,其实也是调用的reactive实现的,有点类似react hooks的useState和useReducer;

5. defineEmits和defineProps获取父组件传过来值和事件

// 第一种不带默认值props
const props = defineProps<{
  foo: string
  bar?: number
}>()
// 第二种带默认值props

export interface ChildProps {
  foo: string
  bar?: number
}

const props = withDefaults(defineProps<ChildProps>(), {
   foo: "1qsd"
   bar?: 3
})

// 第一种获取事件
const emit = defineEmits<{
  (e: 'change', id: number): void
  (e: 'update', value: string): void
}>()

// 第二种获取事件
 
const emit = defineEmits(["dosth"])

6. 使用useAttrs和useSlots

useAttrs 可以获取父组件传过来的id和class等值。
useSlots 可以获得插槽的内容。
例子中,我们使用useAttrs获取父组件传过来的id和class,useSlots获取插槽的内容。
父组件:

<template>

    <div class="father">{{ fatherRef }}</div>

    <Child :fatherRef="fatherRef" @changeVal="changeVal" class="btn" id="111">

        <template #test1>

        <div>1223</div>

        </template>

    </Child>

</template>

<script setup lang="ts">

import { ref } from "vue";

import Child from "./Child.vue";

const fatherRef = ref("1");

function changeVal(val: string) {

    fatherRef.value = val;

}

</script>

<style lang="scss" scoped>

.father {

    margin-top: 40px;

    margin-bottom: 40px;

}

.btn {

    font-size: 20px;

    color: red;

}

</style>

子组件:

<template>

    <!-- <div class="child">{{ props.fatherRef }}</div> -->

    <div v-bind="attrs">

        <slot name="test1">11</slot>

        <input type="text" v-model="inputVal" />

    </div>

</template>

<script setup lang="ts">

import { computed, useAttrs, useSlots } from "vue";

const props = defineProps<{

    fatherRef: string;

}>();

const emits = defineEmits(["changeVal"]);

const slots = useSlots();

const attrs = useAttrs();

console.log(122, attrs, slots);

const inputVal = computed({

    get() {

        return props.fatherRef;

    },

    set(val: string) {

        emits("changeVal", val);

    },

});

</script>


<style lang="scss" scoped>

.child {

}

</style>

使用自定义指令

在setup里边自定义指令的时候,只需要遵循vNameOfDirective 这样的命名规范就可以了

比如如下自定义focus指令,命名就是vMyFocus,使用的就是v-my-focus

自定义指令

<script setup lang="ts">
const vMyFocus = {
  onMounted: (el: HTMLInputElement) => {
    el.focus();
    // 在元素上做些操作
  },
};
</script>
<template>
  <input v-my-focus value="111" />
</template>


7. 使用defineExpose子组件传父组件

子组件

<template>

    <div class="child"></div>

</template>


<script setup lang="ts">

import { ref, reactive } from "vue";

function doSth() {

    console.log(333);

}

defineExpose({ doSth });

</script>


<style lang="scss" scoped>

.child {

}

</style>

父组件

<template>

<div class="father" @click="doSth1">222</div>

    <Child ref="childRef"></Child>

</template>

<script setup lang="ts">

import { ref, reactive } from "vue";

import Child from "./Child.vue";

const childRef = ref();

function doSth1() {

    childRef.value.doSth();

}

</script>

<style lang="scss" scoped>

.father {

}

</style>

8. 父组件传子组件

父组件

<template>

    <div class="father"></div>

    <Child @click="doSth"></Child>

</template>

<script setup lang="ts">

import { ref, reactive } from "vue";

import Child from "./Child.vue";

function doSth() {

    console.log(112);

}

</script>

<style lang="scss" scoped>

.father {

}

</style>

9. toRefs

当从父组件向子组件传props的时候,必须使用toRefs或者toRef进行转一下,这是为什么呢?
这里是因为如果不使用toRefs转一次的话,当父组件中的props改变的时候,子组件如果使用了Es6的解析,会失去响应性。
可以看下如下例子
父组件

<template>

<div class="father" @click="changeVal">{{ fatherRef }}</div>

    <Child :fatherRef="fatherRef"></Child>

</template>

<script setup lang="ts">

import { ref, reactive } from "vue";

import Child from "./Child.vue";

const fatherRef = ref(1);

function changeVal() {

    fatherRef.value = 2;

}

</script>

<style lang="scss" scoped>

.father {

    margin-bottom: 40px;

}

</style>

子组件

<template>

    <div class="child" @click="changeVal">{{ fatherRef }}</div>

</template>

<script setup lang="ts">

import { ref, reactive, onMounted, toRefs } from "vue";

const props = defineProps<{

    fatherRef: any;

}>();

const { fatherRef } = props;

function changeVal() {

    fatherRef.value = 34;
}

</script>

<style lang="scss" scoped>

.child {

}

</style>

可以看到当父组件如果点击之后,因为使用const { fatherRef } = props;进行解析,就失去了响应性
所以当父组件变成2的时候,子组件还是1。
这里有两种解决办法

使用const { fatherRef } = toRefs(props);
在模版中中使用props.fatherRef

10. 子组件使用v-model

10.1 可以在子组件中使用computed,实现双向绑定
父组件

<template>

    <div class="father">{{ fatherRef }}</div>

    <Child :fatherRef="fatherRef" @changeVal="changeVal"></Child>

</template>

<script setup lang="ts">

import { ref } from "vue";

import Child from "./Child.vue";

const fatherRef = ref("1");

function changeVal(val: string) {

    fatherRef.value = val;

}

</script>


<style lang="scss" scoped>

.father {

    margin-top: 40px;

    margin-bottom: 40px;

}

</style>

子组件

<template>

    <!-- <div class="child">{{ props.fatherRef }}</div> -->

    <input type="text" v-model="inputVal" />

</template>

<script setup lang="ts">

import { computed } from "vue";

const props = defineProps<{

    fatherRef: string;

}>();

const emits = defineEmits(["changeVal"]);


const inputVal = computed({

    get() {

        return props.fatherRef;

    },

    set(val: string) {

        emits("changeVal", val);

    },

});

</script>

<style lang="scss" scoped>

.child {

}

</style>

10.2 可以从父组件传递值和改变值的方法,然后子组件也可以使用v-model
例子中父组件传递 modelValue和update:modelValue方法 父组件:

<template>

    <Child :modelValue="searchText" @update:modelValue="changeVal"> </Child>

</template>

<script setup lang="ts">

import { ref } from "vue";

import Child from "./Child.vue";

const searchText = ref(1);

function changeVal(val: number) {

    searchText.value = val;

}

</script>

<style lang="scss" scoped>

.father {

    margin-top: 40px;

    margin-bottom: 40px;

}

.btn {

    font-size: 20px;

    color: red;

}

</style>

子组件:

<template>

    <!-- <div class="child">{{ props.fatherRef }}</div> -->

    <!-- <div v-bind="attrs">

        <slot name="test1">11</slot>

        <input type="text" v-model="inputVal" />

    </div> -->

    <input v-model="modelValue" />

</template>


<script setup lang="ts">

import { computed, useAttrs, useSlots } from "vue";

const props = defineProps<{

    modelValue: number;

}>();

// const emits = defineEmits(["changeVal"]);

</script>


<style lang="scss" scoped>

.child {

}

</style>

11. 递归组件

组件本身是可以调用组件自身的,也就是递归。 比如名为 Child.vue 的组件可以在其模板中用 引用它自己。这里需要注意的是需要设置条件语句,用来中断递归,不然递归会无限递归下去。

父组件

<template>
  <Child :modelValue="searchText" @update:modelValue="changeVal"> </Child>
</template>

<script setup lang="ts">
import { ref } from "vue";
import Child from "./Child.vue";
const searchText = ref(1);
function changeVal(val: number) {
  searchText.value = val;
}
</script>

<style lang="scss" scoped>
.father {
  margin-top: 40px;
  margin-bottom: 40px;
}
.btn {
  font-size: 20px;
  color: red;
}
</style>

子组件

<template>
  <input v-model="modelValue" />
  <Child
    :modelValue="test"
    @update:modelValue="changeTest"
    v-if="modelValue > 2"
  ></Child>
</template>

<script setup lang="ts">
import { computed, useAttrs, useSlots, ref } from "vue";
const props = defineProps<{
  modelValue: number;
}>();
const test = ref(0);
function changeTest(val: number) {
  test.value = val;
}

// const emits = defineEmits(["changeVal"]);
</script>

<style lang="scss" scoped>
.child {
  position: relative;
}
</style>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/384103.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

微服务架构简介

微服务 软件架构是一个包含各种组织的系统组织&#xff0c;这些组件包括 Web服务器, 应用服务器, 数据库,存储, 通讯层), 它们彼此或和环境存在关系。系统架构的目标是解决利益相关者的关注点。 image Conway’s law: Organizations which design systems[...] are constrained…

jenkins集成tapd插件

文章目录1. 在tapd上关联jenkins1.1 公司管理员登录tapd&#xff0c;进入设置—开发集成—服务集成1.2 下载插件&#xff0c;并在jenkins上安装。2. 在tapd上关联jenkins在jenkins配置tapd插件2.1 生成Jenkins API Token3. 进入某个项目&#xff0c;启用流水线并配置3.1 选择je…

第二章 opengl实现三角形

OpenGL三角形关注参数图形渲染管线顶点输入顶点着色器编译着色器片段着色器着色器程序链接顶点属性元素缓冲对象三角形关注参数 顶点数组对象&#xff1a;Vertex Array Object&#xff0c;VAO 顶点缓冲对象&#xff1a;Vertex Buffer Object&#xff0c;VBO 元素缓冲对象&…

Windows10下使用Intel SGX功能(二):helloworld流程分析

文章目录参考文献helloworld 代码解读代码目录结构调用流程1. 首先定义 host 和 enclave 之间相互调用的函数2. 实现 enclave 端的 enclave_helloworld() 逻辑3. 实现 host 端的 host_helloworld() 逻辑4. 编译 enclave 应用程序4.1 使用 oeedger8r 编译 helloworld.edl 的 unt…

学生专用台灯怎么选?给孩子买台灯需要注意什么

台灯是现在很多学生孩子都使用比较多的产品&#xff0c;晚上看书学习&#xff0c;停笔沉思&#xff0c;台灯柔和舒适的光照&#xff0c;可以营造良好的氛围&#xff0c;也能有效保护眼睛&#xff0c;不受光线刺激、辐射伤害。 那么学生专用台灯该怎么选呢&#xff1f; ①一个…

捍宇医疗再冲刺科创板上市:核心产品专利来自购买,暂未商业化

2023年3月1日&#xff0c;上海捍宇医疗科技股份有限公司&#xff08;下称“捍宇医疗”&#xff09;递交招股书&#xff0c;准备在科创板上市。据贝多财经了解&#xff0c;捍宇医疗曾冲刺港交所上市&#xff0c;并于2021年9月通过聆讯&#xff0c;但最终放弃了港交所上市的打算。…

后端必备之Vue基础【黑马程序员】

黑马程序员4小时入门Vue传送门 1. 简介 Vue是一个操作JavaScript的框架&#xff0c;类似于jQuery&#xff0c;但比jQuery好用&#xff0c;是现在的主流 2. 测试例子 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8" /&…

LeetCode-746. 使用最小花费爬楼梯

题目来源 746. 使用最小花费爬楼梯 动态规划 动态规划五部曲 1.确定dp数组以及下标的含义 使用动态规划&#xff0c;就要有一个数组来记录状态&#xff0c;本题只需要一个一维数组dp[i]就可以了。 dp[i]的定义&#xff1a;到达第i台阶所花费的最少体力为dp[i]。 2.确定递推…

The simplest way to get started with Stable Diffusion on Ubuntu

link1 link2 Stable Diffusion is a machine learning model that can generate images from natural language descriptions. Because it’s open source, it’s also easy to run it locally, which makes it very convenient to experiment with in your own time. The sim…

万字长文漫谈高可用高并发技术

互联网应用通常面向海量用户&#xff0c;其后台系统必须支撑高并发请求。在后端开发面试中&#xff0c;高并发技术也是一个常见的考察点。 那么&#xff0c;高并发系统通常是怎么设计的呢&#xff1f;需要采用哪些技术呢&#xff1f;本文就简单聊一聊高并发背后的各种技术栈。…

蓝桥杯任意刷

这里写目录标题受伤的皇后全球变暖&#xff08;最大联通子集&#xff0c;一趟递归记得不要嵌套计数&#xff09;游园问题金额查错蓝肽子序列&#xff08;最长公共子序列&#xff09;受伤的皇后 #include <iostream> #include <bits/stdc.h> using namespace std; …

运动带什么蓝牙耳机好,最适合运动佩戴的蓝牙耳机分享

运动时汗如雨下&#xff01;这可如何是好&#xff0c;这时候一款运动专用的防水耳机就成为人们的最爱。现在&#xff0c;市面上的耳机种类已经多到数不胜数。价格也不一&#xff0c;到底是一分钱一分货&#xff0c;还是打着低价卖你一个小型音响。到底怎么挑才能找到一款性价比…

联邦学习(fate)从主机安装到实现联邦学习

联邦学习&#xff08;fate&#xff09;从主机安装到实现联邦学习一、单机部署1.1虚拟机配置1.2安装python1.3端口检查1.4获取安装包&#xff0c;并解压1.5安装1.6启动1.7测试1.8安装FATE-Client、FATE-Test、FATE-Flow、jupyter notebook1.8.1FATE-Client、FATE-Test1.8.2FATE-…

Newman+Jenkins实现接口自动化测试

一、是什么Newman Newman就是纽曼手机这个经典牌子&#xff0c;哈哈&#xff0c;开玩笑啦。。。别当真&#xff0c;简单地说Newman就是命令行版的Postman&#xff0c;查看官网地址。 Newman可以使用Postman导出的collection文件直接在命令行运行&#xff0c;把Postman界面化运…

【C++】stack 与 queue

stack 与 queuestackSTL 容器中 stack 的使用模拟实现 stackqueueSTL 容器中 queue 的使用模拟实现 queuestack 在数据结构中&#xff0c;我们了解到&#xff0c;stack 栈结构&#xff0c;是一种先进后出的结构&#xff0c;并且我们是使用顺序表来进行实现栈的操作的。 STL 容…

如何使用FindFunc在IDA Pro中寻找包含指定代码模式的函数代码

关于FindFunc FindFunc是一款功能强大的IDA Pro插件&#xff0c;可以帮助广大研究人员轻松查找包含了特定程序集、代码字节模式、特定命名、字符串或符合其他各种约束条件的代码函数。简而言之&#xff0c;FindFunc的主要目的就是在二进制文件中寻找已知函数。 使用规则过滤 …

C++回顾(六)—— 对象动态建立

6.1 new 和 delete 用法 6.1.1 概述 在软件开发过程中&#xff0c;常常需要动态地分配和撤销内存空间&#xff0c;例如对动态链表中结点的插入与删除。在C语言中是利用库函数malloc和free来分配和撤销内存空间的。C提供了较简便而功能较强的运算符new和delete来取代malloc和f…

smart-doc Java Restful API 文档生成工具

smart-doc简介 官方地址smart-doc smart-doc 是一款同时支持 JAVA REST API 和 Apache Dubbo RPC 接口文档生成的工具&#xff0c;smart-doc 在业内率先提出基于 JAVA 泛型定义推导的理念&#xff0c; 完全基于接口源码来分析生成接口文档&#xff0c;不采用任何注解侵入到业…

vue基础学习笔记

1.v-text 设置标签的文本值&#xff0c;将标签内的内容完全替换为v-text绑定的值。 如果想要保留标签内的值&#xff0c;可以采用差值表达式的方式&#xff08;<h2>text{{message}}</h2>&#xff09; 内部值支持拼接 <!DOCTYPE html> <html lang"en…

Unity Asset Bundle学习 - 加载网络资源

昨天调试了一下加载本地资源 Unity Asset Bundle学习 - 加载本地资源 今天试一下用Asset Bundle加载网络数据 接着按照文档走 发现 有问题 引用命名空间一直报错 按文档走不通 就直接百度查了 查了好多 这个东西有很多前辈的经验 直接拷贝代码拿过来用的 下面这段是测试没问题…