首页 > 作文

vue3+TypeScript+vue

更新时间:2023-04-04 11:27:40 阅读: 评论:0

简单使用

创建项目

vue-cli创建

$npm install -g @vue/cli$vue --version@vue/cli 4.5.15$vue create my-project

然后的步骤:

plea pick a pret
选择 manually lect featurescheck the features needed for your project
选择上typescript,特别注意点空格是选择,点回车是下一步choo a version of vue.js that you want to start the project with
选择 3.x (preview)u class-style component syntax
直接回车u babel alongside typescript
直接回车pick a linter / formatter config
直接回车u history mode for router?
直接回车pick a linter / formatter config
直接回车pick additional lint features
直接回车where do you prefer placing config for babel, eslint, etc.?
直接回车save this as a pret for future projects?
直接回车

文件结构:

my-project+--- babel.config.js+--- package-lock.json+--- package.json+--- public|   +--- favicon.ico|   +--- index.html+--- readme.md+--- src|   +--- app.vue|   +--- asts|   |   +--- logo.png|   +--- components|   |   +--- helloworld.vue|   +--- main.ts|   +--- shims-vue.d.ts+--- tsconfig.json+--- node_modules|   +--- ...

入口文件为src/main.ts

vite创建

执行以下命令创建项目

$npm init vite-app <project-name>$cd <project-name>$npm install$npm run dev

文件结构:

project-name+--- index.html+--- package-lock.json+--- package.json+--- public|   +--- favicon.ico+--- src|   +--- app.vue|   +--- asts|   |   +--- logo.png|   +--- components|   |   +--- helloworld.vue|   +--- index.css|   +--- main.js+--- node_modules|   +--- ...

入口文件为src/main.ts

注意: 由于使用vite方法创建的项目没有vue的声明文件, 所以需要我们自定义, 否则会报错.
src/shims-vue.d.ts

/* eslint-disable */declare module '*.vue' {  import type { definecomponent } from 'vue'  const component: definecomponent<{}, {}, any>  export default component}

安装vue-router

$npm install vue-router@4

至此, package.json如下:

{  "name": "my-project",  "version": "0.1.0",  "private": true,  "scripts": {    "rve": "vue-cli-rvice rve",    "build": "vue-cli-rvice build",    "lint": "vue-cli-rvice lint"  },  "dependencies": {    "core-js": "^3.6.5",    "vue": "^3.0.0",    "vue-router": "^4.0.12"  },  "devdependencies": {    "@typescript-eslint/eslint-plugin": "^4.18.0",    "@typescript-eslint/parr": "^4.18.0",    "@vue/cli-plugin-babel": "~4.5.0",    "@vue/cli-plugin-eslint": "~4.5.0",    "@vue/cli-plugin-typescript": "~4.5.0",    "@vue/cli-rvice": "~4.5.0",    "@vue/compiler-sfc": "^3.0.0",    "@vue/eslint-config-typescript": "^7.0.0",    "eslint": "^6.7.2",    "eslint-plugin-vue": "^7.0.0",    "typescript": "~4.1.5"  }}

创建/修改组件

创建src/router/index.ts

import { createrouter, createwebhashhistory } from "vue-router" import home from '../components/home.vue'import about from '../components/about.vue'import ur from '../components/ur.vue' const routes = [// router参数详细看下文{path: "/home",name: "home",component: home},{path: "/about",name: "about",component: about},{path: "/ur/:uid",  // 动态参数name: "ur",component: ur}]export const router = createrouter({history: createwebhashhistory(),routes: routes})

创建组件: home.vue about.vue ur.vue

src/components/home.vue

<template>  <div>home组件</div></template> <script lang="ts">import { definecomponent } from "vue"; export default definecomponent({  name: "home",  tup() {return {  // 返回的数据};  },});</script>

src/components/about.vue

<template>  <div>about组件</div></template> <script lang="ts">import { definecomponent }博士研究生和博士的区别 from "vue"; export default definecomponent({  name: "about",  tup() {return {  // 返回的数据};  },});</script>

src/components/ur.vue

<template>  <div>ur组件</div></template> <script lang="ts">import { definecomponent } from "vue"; export default definecomponent({  name: "ur",  tup() {return {  // 返回的数据};  },});</script>

修改app.vue

<template>  <div>{{ appmessage }}</div>  <!-- router-link会被渲染成a标签 -->我想对你说作文600字;  <router-link to="/home">home</router-link>  <router-link to="/about">about</router-link>  <router-link to="/ur/lczmx">ur</router-link>   <!-- 路由出口 -->  <!-- 路由匹配到的组件将渲染在这里 -->  <router-view></router-view></template> <script lang="ts">import { definecomponent } from "vue"; export default definecomponent({  name: "app",  tup() {const appmessage = "app组件";return {  // 返回的数据  appmessage,};  },});</script><style>/* 添加样式 */#app {  text-align: center;  margin-top: 50px;}a {  margin: 30px;  display: inline-block;}</style>

修改入口ts

修改src/main.ts

import { createapp } from 'vue'import app from './app.vue'import './index.css' import { router } from './router' // 创建应用 返回对应的实例对象const app = createapp(app) // 安装 vue-router 插件app.u(router)// 调用mount方法app.mount('#app')

启动vue

$npm run rve> my-project@0.1.0 rve> vue-cli-rvice rve  info  starting development rver...98% after emitting copyplugin done  compiled successfully in 6387ms                                                                                               下午4:14:30  app running at:  - local:   http://localhost:8080/  - network: http://192.168.43.12:8080/  note that the development build is not optimized.  to create a production build, run npm run build.no issues found.

在浏览器中访问

根据提示, 访问http://localhost:8080/, 如下图

文件结构图片

综合使用

动态参数

假如我们需要的路由是: /ur/lczmx/ur/jack, 但是我们明显不可能为这两个路由定义两个不同的组件, 最好的方法就是使用动态参数:

const routes = [  // 动态段以冒号开始  { path: '/urs/:id', component: ur },  // 使用正则表达式  `()` 里面的东西会传给前面的pathmatch  // 值在route.params.pathmatch下  { path: '/:pathmatch(.*)*', name: 'notfound', component: notfound },]

匹配时, 会将参数映射到router实例的currentroute.value.params

注意vue2中: 由于在tup无法使用this.$routethis.$router
至于如何获取, 看我的另一篇博客: 和 官网: vue router 和 组合式 api

匹配列表

匹配模式匹配路径当前路由的参数/urs/:urname/urs/eduardo{ urname: 'eduardo' }/urs/:urname/posts/:postid/urs/eduardo/posts/123{ urname: 'eduardo', postid: '123' }

在使用带有参数的路由时需要注意: 由于相同的组件实例将被重复使用,所以组件的生命周期钩子不会被调用

但是我们可以对路由进行监听

使用watch监听动态参数

修改src/components/ur.vue:

<template>  <div>ur组件</div>  <p>当前用户: {{ uid }}</p>   <router-link to="/ur/lczmx">lczmx</router-link>  <router-link to="/ur/jack">jack</router-link></template> <script lang="ts"专科专业>import { definecomponent, watch, ref } from "vue";import { urouter } from "vue-router"; export default definecomponent({  name: "ur",  tup() {    const router = urouter();    const uid = ref(router.currentroute.value.params.uid);    watch(      // 监听非响应式数据      () => router.currentroute.value,      (val) => {        // 修改uid        uid.value = val.params.uid;      }    );    return {      // 返回的数据      uid,    };  },});</script>

使用组合api监听动态参数

https://next.router.vuejs.org/zh/guide/advanced/composition-api.html

重定向

下面使用router的全部参数:

const routes = [    {        path: "/",        // 写法1 写死url        // redirect: "/home", // 访问 "/" 时 跳转到 "/home"         // 写法2 跳转到对应的命名路由        redirect: { name: "home" },         // 写法3 定义一个方法// 该方法亦可以 返回一个相对路径        /*        redirect: to => {            // 方法接收目标路由作为参数 "to"             // return 重定向的字符串路径/路径对象// query指定参数            return { path: '/home', query: { q: to.params.archtext } }        },        */    },    {        path: "/home",        name: "home",        component: home    }]

注意, 重定向不会触发 导航守卫

另附官网的例子: named views – vue router 4 examples

命名与别名

命名路由

给路由一个名称, 可以在其他路由中使用, 如: redirectrouter-link

const routes = [  {    path: '/ur/:urname',    name: 'ur',    component: ur  }]

redirect的使用如上文, 而router-link如下:

<template>  <div>ur组件</div>  <p>当前用户: {{ uid }}</p>   <router-link :to="{ name: 'ur', params: { uid: 'lczmx' } }"    >lczmx</router-link  >  <router-link :to="{ name: 'ur', params: { uid: 'jack' } }"    >jack</router-link  ></template>

router.push(routerrouter对象)中使用:

router.push({ name: 'ur', params: { uid: 'lczmx' } })

命名视图

即, 我们可以router-view定义一个名字, 已达到实现可复用的效果
我们可以使用这个功能实现 一个侧边栏等

举个例子

定义路由:

import { createrouter, createwebhashhistory } from "vue-router" import home from '../components/home.vue'import about from '../components/about.vue'import ur from '../components/ur.vue' const routes = [{path: "/",components: {default: home,  // 默认用home组件a: about,  // a用about组件b: ur,  // b用ur组件}, },{path: "/home",components: {default: about,   // 默认用about组件a: home,  // a用home组件b: ur,  // b用ur组件}, },]  export const router = createrouter({history: createwebhashhistory(),routes: routes})

修改app.vue

<template>  <div>{{ appmessage }}</div>   <!-- router-link会被渲染成a标签 -->  <router-link to="/">/</router-link>  <router-link to="/home">/home</router-link>   <!-- 路由出口 -->  <!-- 路由匹配到的组件将渲染在这里 -->  <!-- default -->  <router-view></router-view>  <router-view name="about"></router-view>  <router-view name="ur"></router-view></template> <script lang="ts">import { definecomponent } from "vue"; export default definecomponent({  name: "app",  tup() {const appmessage = "app组件";return {  // 返回的数据  appmessage,};  },});</script><style>/* 添加样式 */#app {  text-align: center;  margin-top: 50px;}a {  margin: 30px;  display: inline-block;}</style>

其他组件
about.vue:

<template>  <div>about组件</div></template>

home.vue:

<template>  <div>home组件</div></template>

ur.vue

<template>  <div>ur组件</div></template>

启动服务并访问vue

如图:

假如不指定视图名, 那么为default

别名

可以实现 不同url 访问同一路由的效果

const routes = [    // 可以访问 "/home" 也可以访问 "/"    // 且访问的路径不会改变    {        path: "/home",        name: "home",        component: home,        alias: "/"    }

嵌套路由

之前我们在app.vue中定义router-view, 让其他组件在哪里渲染

但假如我们需要在其他组件中渲染的话, 就需要嵌套路由了

使用children嵌套路由, 它的值是路由数据, 就好像外部的router那样定义

例子:

router.index.ts

import { createrouter, createwebhashhistory } from "vue-router" import home from '../components/home.vue'import about from '../components/about.vue'import ur from '../components/ur.vue'import urhome from '../components/urhome.vue'import urttings from '../components/urttings.vue'import urprofile from '../components/urprofile.vue' const 司法体制routes = [// 可以访问 "/home" 也可以访问 "/"// 且访问的路径不会改变{path: "/home",name: "home",component: home,alias: "/"},{path: "/about",name: "about",component: about},{path: "/ur/:uid",  // 动态参数name: "ur",component: ur,  // 内部有router-view渲染要嵌套的路由children: [// 匹配形如 /ur/lczmx 的url{ path: "", component: urhome }, // 匹配形如 /ur/lczmx/ttings 的url{ path: "ttings", component: urttings, name: "ur-ttings" }, // 匹配形如 /ur/lczmx/profile 的url{ path: "profile", component: urprofile, name: "ur-profile" }]}]  export const router = createrouter({history: createwebhashhistory(),routes: routes})

注意: 假如children中没有path: ""的话, 那么访问/ur/lczmx, 只能得到一个页面空白

ur.vue

<template>  <div><router-link :to="{ name: 'ur-ttings' }">ttings</router-link><router-link :to="{ name: 'ur-profile' }">profile</router-link>  </div>   <router-view></router-view></template>

urhome.vue

<template>  <div>用户主页</div></template>

urprofile.vue

<template>  <div>用户详细信息页面</div></template>

urttings.vue

<template>  <div>用户设置页面</div></template>

启动并访问

在浏览器中测试:

编程式路由

即不通过a标签, 而是带无的成语通过js/ts改变路由, 原理是向history栈添加一个新的记录
在vue3中, 有以下写法

<template>  <div>about组件</div>  <button @click="changerouter">修改路由</button></template>  <script lang="ts">import { definecomponent } from "vue"; import { urouter } from "vue-router"; export default definecomponent({  name: "about",  tup() {    // 获得router对象    const router = urouter();     const changerouter = () => {      /* 修改路由的例子 */       // 1 字符串路径      router.push("/urs/lczmx");       // 2 带有路径的对象      router.push({ path: "/urs/lczmx" });       // 3 命名的路由,并加上参数,让路由建立 url      router.push({ name: "ur", params: { urname: "lczmx" } });       // 4 带查询参数,结果是 /register?plan=private      router.push({ path: "/register", query: { plan: "private" } });       // 5 带 hash,结果是 /about#team      router.push({ path: "/about", hash: "#team" });       // 6 我们可以手动建立 url,但我们必须自己处理编码      const urname = "lczmx";      router.push(`/ur/${urname}`); // -> /ur/lczmx      // 同样      router.push({ path: `/ur/${urname}` }); // -> /ur/lczmx      // 如果可能的话,使用 `name` 和 `params` 从自动 url 编码中获益      router.push({ name: "ur", params: { urname } }); // -> /ur/lczmx       // 7 `params` 不能与 `path` 一起使用, 否则 `params` 将会被忽略      router.push({ path: "/ur", params: { urname } }); // -> /ur       // 8 replace为true 不向history 中添加      router.push({ path: "/home", replace: true });      // 等同于      router.replace({ path: "/home" });       // 9 横跨历史      // 向前移动一条记录,与 router.forward() 相同      router.go(1);      // 返回一条记录,与router.back() 相同      router.go(-1);      // 前进 3 条记录      router.go(3);      // 如果没有那么多记录,静默失败      router.go(-100);      router.go(100);    };    return {      // 返回的数据      changerouter,    };  },});</script> <style>button {  margin: 30px;}</style>

更多见vue-router4官网: vue router

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。

本文发布于:2023-04-04 11:27:14,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/22b77b2c8b239cabdd7156e33e2b8139.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:vue3+TypeScript+vue.doc

本文 PDF 下载地址:vue3+TypeScript+vue.pdf

标签:路由   组件   参数   路径
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图