zl程序教程

您现在的位置是:首页 >  APP

当前栏目

Vue3.0 起跑 搭建项目后应用 系列二

2023-02-25 18:20:44 时间

Vue3.0部分知识点

项目目录结构

|-node_modules       -- 所有的项目依赖包都放在这个目录下
|-public             -- 公共文件夹
---|favicon.ico      -- 网站的显示图标
---|index.html       -- 入口的html文件
|-src                -- 源文件目录,编写的代码基本都在这个目录下
---|assets           -- 放置静态文件的目录,比如logo.pn就放在这里
---|components       -- Vue的组件文件,自定义的组件都会放到这
---|App.vue          -- 根组件,这个在Vue2中也有
---|main.ts          -- 入口文件,因为采用了TypeScript所以是ts结尾
---|shims-vue.d.ts   -- 类文件(也叫定义文件),因为.vue结尾的文件在ts中不认可,所以要有定义文件
|-.browserslistrc    -- 在不同前端工具之间公用目标浏览器和node版本的配置文件,作用是设置兼容性
|-.eslintrc.js       -- Eslint的配置文件,不用作过多介绍
|-.gitignore         -- 用来配置那些文件不归git管理
|-package.json       -- 命令配置和包管理文件
|-README.md          -- 项目的说明文件,使用markdown语法进行编写
|-tsconfig.json      -- 关于TypoScript的配置文件
|-yarn.lock          -- 使用yarn后自动生成的文件,由Yarn管理,安装yarn包时的重要信息存储到yarn.lock文件中  

1. package.json三个命令

{
"scripts": {
    "serve": "vue-cli-service serve",   在开发时用于查看效果的命令,视频中演示看一下效果
    "build": "vue-cli-service build",   打包打码,一般用于生产环境中使用
    "lint": "vue-cli-service lint"      检查代码中的编写规范
},
开发环境 devDependencies 编写代码、测试代码、修改 Bug。也就说这些代码没有上线。
测试环境 dependencies    就是代码已经上线,放到了正式的服务器上。
}

2. main.ts文件

import { createApp } from "vue"; // 引入vue文件,并导出`createApp`
import App from "./App.vue"; // 引入自定义组件,你在页面上看的东西基本都在这个组件里

createApp(App).mount("#app"); // 把App挂载到#app节点上,在public目录下的index.html找节点

setup() ref()

setup() //代替data和method返回数据和方法,在beforeCreate、created之前执行 setup()函数的用法,可以代替 Vue2 中的 date 和 methods 属性,直接把逻辑卸载 setup 里就可以

ref 函数的使用,它是一个神奇的函数,要在template中使用的变量,必须用ref包装一下。 return出去的数据和方法,在模板中才可以使用,这样可以精准的控制暴漏的变量和方法。

defineComponent重载函数

<script lang="ts">
    import { defineComponent, ref } from "vue";
    export default defineComponent({
    name: "App",
    setup() {
        const aa = ref(["11", "22", "33"]); //无初始值设置为null
        return {
        aa
        };

    <!-- const divs = ref([])
        组件挂载后,即能通过divs.value获取遍历元素的所有dom
        return{
            divs
    } -->

    },
    });
</script>
```html
# reactive()函数优化
    reactive()函数接收一个普通对象,返回一个响应式的数据对象。用户数据生成代理对象,从而实现监控用户数据改变的目的。
```html
<script lang="ts">
    import { ref, reactive } from "vue";
    export default {
    name: "App",
    setup() {
        const data = reactive({
        const aa = ref(["11", "22", "33"]);
        });

        return {
        data,
        };
    },
    };
</script>
ref(),reactive() //定义vue2.0中data和method方法

toRefs()优化

toRefs()函数可以将reactive()创建出来的响应式对象,转换为普通对象,只不过这个对象上的每个属性节点,都是ref()类型的响应式数据 toRefs() //使用拓展用算符…的方法返回数据data

import { reactive, toRefs } from "vue";
export default {
name: "App",
setup() {
    const data: DataProps = reactive({
    const aa = ref(["11", "22", "33"]);
    });
    const refData = toRefs(data);
    return {
    ...refData,
    };
},
};

watch-监听器(侦听器)

(1)不会立即执行,当侦听的源变更时才会执行
(2)可以监听多个数据源

import {… , watch} from “vue” 引入后编写watch函数,它接受两个参数,第一个是要监听的值overText,然后是一个回调函数。在函数中你可以获得到新知和老值。 定义一个方法 使用watch同样需要先进行导入.

import { watch } from 'vue'
const overAction = () => {
overText.value = overText.value;
};
return {  overAction};
}
watch(aa, (newValue, oldValue) => {
document.title = newValue;
});

如果监听多个值
watch([overText, () => data.select], (newValue, oldValue) => {
console.log(`new--->${newValue}`);
console.log(`old--->${oldValue}`);
document.title = newValue[0];
});

vue3生命周期

setup() :开始创建组件之前,在beforeCreate和created之前执行。创建的是data和method

onBeforeMount() : 组件挂载到节点上之前执行的函数。
onMounted() : 组件挂载完成后执行的函数。
onBeforeUpdate(): 组件更新之前执行的函数。
onUpdated(): 组件更新完成之后执行的函数。
onBeforeUnmount(): 组件卸载之前执行的函数。
onUnmounted(): 组件卸载完成后执行的函数
onActivated(): 被包含在<keep-alive>中的组件,会多出两个生命周期钩子函数。被激活时执行。
onDeactivated(): 比如从 A 组件,切换到 B 组件,A 组件消失时执行。
onErrorCaptured(): 当捕获一个来自子孙组件的异常时激活钩子函数(以后用到再讲,不好展现)。

注:使用组件会将数据保留在内存中,比如我们不想每次看到一个页面都重新加载数据,就可以使用组件解决。

先列举5个常用得

<script lang="ts">
import {
reactive,
toRefs,
onMounted,
onBeforeMount,
onBeforeUpdate,
onUpdated,
} from "vue";

const app = {
name: "App",
setup() {
    const data: DataProps = reactive({
    const aa = ref(["11", "22", "33"]);
    });
    onBeforeMount(() => {
    console.log("2-组件挂载到页面之前执行-----onBeforeMount()");
    });
    onMounted(() => {
    console.log("3-组件挂载到页面之后执行-----onMounted()");
    });
    onBeforeUpdate(() => {
    console.log("4-组件更新之前-----onBeforeUpdate()");
    });
    onUpdated(() => {
    console.log("5-组件更新之后-----onUpdated()");
    });
    const refData = toRefs(data);
    return {
    ...refData,
    };
},
};
export default app;

结果:

1 - 开始创建组件---- - setup();
2 - 组件挂载到页面之前执行---- - onBeforeMount();
3 - 组件挂载到页面之后执行---- - onMounted();
4 - 组件更新之前---- - onBeforeUpdate();
5 - 组件更新之后---- - onUpdated();

vue2得生命周期在vue3 也可以用 但是不愿混用

你可以在setup()函数之后编写Vue2的生命周期函数,代码如下:

beforeCreate() {
console.log("1-组件创建之前-----beforeCreate()");
},
beforeMount() {
console.log("2-组件挂载到页面之前执行-----BeforeMount()");
},
mounted() {
console.log("3-组件挂载到页面之后执行-----Mounted()");
},
beforeUpdate() {
console.log("4-组件更新之前-----BeforeUpdate()");
},
updated() {
console.log("5-组件更新之后-----Updated()");
},

Vue2.x 与 Vue3.x的生命周期钩子函数

Vue2--------------vue3
beforeCreate  -> setup()
created       -> setup()
beforeMount   -> onBeforeMount
mounted       -> onMounted
beforeUpdate  -> onBeforeUpdate
updated       -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed     -> onUnmounted
activated     -> onActivated
deactivated   -> onDeactivated
errorCaptured -> onErrorCaptured

钩子函数的使用

1. onRenderTracked直译过来就是状态跟踪——-散弹枪

它会跟踪页面上所有响应式变量和方法的状态,也就是我们用return返回去的值,他都会跟踪。只要页面有update的情况,他就会跟踪,然后生成一个event对象,我们通过event对象来查找程序的问题所在。

使用onRenderTracked同样要使用import进行引入。
import { .... ,onRenderTracked,} from "vue";

引用后就可以在setup()函数中进行引用了。
onRenderTracked((event) => {
console.log("状态跟踪组件----------->");
console.log(event);
});

在组件没有更新的时候onRenderTracked是不会执行的,组件更新时,他会跟组里边每个值和方法的变化。

2. onRenderTriggered直译过来是状态触发——-狙击枪

它不会跟踪每一个值,而是给你变化值的信息,并且新值和旧值都会给你明确的展示出来。 
import { .... ,onRenderTriggered,} from "vue";

onRenderTriggered()函数,写在setup()函数里边,
onRenderTriggered((event) => {
console.log("状态触发组件--------------->");
console.log(event);
});

对 event 对象属性的详细介绍:

- key 那边变量发生了变化
- newValue 更新后变量的值
- oldValue 更新前变量的值
- target 目前页面中的响应变量和函数

vue3模块化

1. 新建一个ts文件

直接上代码,在src目录下,新建一个文件夹host(所有抽离出来的功能模块都可以放到这个文件夹里),然后再新建一个ts文件

import { ref } from "vue";    //在代码的最前面用import进行引入ref
const nowTime = ref("00:00:00");
const getNowTime = () => {
    const now = new Date();
    const hour = now.getHours() < 10 ? "0" + now.getHours() : now.getHours();
    const minu =
        now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes();
    const sec =
        now.getSeconds() < 10 ? "0" + now.getSeconds() : now.getSeconds();
    nowTime.value = hour + ":" + minu + ":" + sec;

    setTimeout(getNowTime, 1000);
};
export { nowTime, getNowTime } //,在最后用export的方式

2.APP.vue页面

引入代码:

<template>
<div>
    <div>{{ nowTime }}</div>
    <div><button @click="getNowTime">显示时间</button></div>
</div>
</template>
<script lang="ts">
import { nowTime, getNowTime } from "./host/useNowTime"

import {
    defineComponent,
    ref,
} from 'vue';
export default defineComponent({
    name: 'App',
    components: {
    },
    setup() {
        return{
            nowTime,getNowTime
        }
    }
});
</script>

简单的弹框组件

1.在/src/components/目录下,创建一个Dialog.vue的组件

<template>
<div id="center">
    <h2>显示的内容</h2>
</div>
</template>
<script lang="ts">
export default {};
</script>
<style>
#center {
width: 200px;
height: 200px;
border: 2px solid black;
background: white;
position: fixed;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
</style>

2.在App.vue中使用

import modal from "./components/Dialog.vue";
const app = {
	 name: "App",
	 components: {
	     Dialog,
	 },
}

Suspense组件的使用

使用方法一:<Suspense></Suspense>与插槽配合
Suspense是有两个template插槽的,第一个default代表异步请求完成后,显示的模板内容。fallback代表在加载中时,显示的模板内容。

1.1定义组件

<template>
<h1>{{result}}</h1>
</template>
<script>
export default {
    name: "NewModel",
    setup(){
        return new Promise((resolve)=>{
            setTimeout(()=>{
                return resolve({result:"OK"})
            },3000)
        })
    }
}
</script>

1.2使用suspense组件渲染效果

<suspense>
    <template #default>
        <new-model></new-model>
    </template>
    <template #fallback>
        <h1>Loadding...</h1>
    </template>
</suspense>

结果三秒之前显示Loadding… ,三秒之后显示组件内容;(成功后显示组件内容)

2.1定义异步组件

Suspense也是支持async…await的语法的,所以这个组件就用async的写法来写。

<template>
    <img :src="result%20&&%20result.imgUrl"  />
</template>
<script lang="ts">
import axios from 'axios'
import { defineComponent } from 'vue'
export default defineComponent({
    async setup() {  //promise 语法糖  返回之后也是promise对象
        const rawData = await  axios.get('https://apiblog.jspang.com/default/getGirl')
        return {result:rawData.data}
    }
})

2.2 引入组件使用

导入组件  注册组件后
<template>
<div>
    <Suspense>
    <template #default>
        <girl-show />
    </template>
    <template #fallback>
        <h1>Loading...</h1>
    </template>
    </Suspense>
</div>
</template>

3. 异步错误处理

可以使用onErrorCaptured这个钩子函数来捕获异常 引入. import { ref , onErrorCaptured} from “vue”; 有了onErrorCaptured就可以直接在setup()函数中直接使用了。钩子函数要求我们返回一个布尔值,代表错误是否向上传递。

setup() {
    onErrorCaptured((error) => {
    console.log(`error====>`,error)
    return true  
    })
    return {};
},
<template>
    <template #fallback>
        <h1>Loading...</h1>
    </template>
    </Suspense>
</div>
</template>

3. 异步错误处理

可以使用onErrorCaptured这个钩子函数来捕获异常 引入. import { ref , onErrorCaptured} from “vue”; 有了onErrorCaptured就可以直接在setup()函数中直接使用了。钩子函数要求我们返回一个布尔值,代表错误是否向上传递。

setup() {
    onErrorCaptured((error) => {
    console.log(`error====>`,error)
    return true  
    })
    return {};
},
</script>