Vue3一些基本概念(一)

115 阅读5分钟

Vue3

Vue3生命周期

beforeCreate

date挂载之前

created

在vue3中在setup()方法里面就相当于created和beforeCreate 。

date挂载了。在created之前模板语法都没有渲染。

beforeMounted

在页面渲染之前。

mounted

页面渲染结束。

我们来看一下如下示例:

<template>
  <div class="about">
    <h1>vue3生命周期</h1>
    <div id="hi">{{msg}}</div>
  </div>
</template>
<script>
import {onBeforeMount, onMounted, reactive, toRefs} from "vue";

  export default {
    name:"666",
    setup(){
      const data = reactive({
        msg:"hello"
      })
      onBeforeMount(()=>{
        console.log("onBeforeMount",document.getElementById("hi"))
      })

      onMounted(()=>{
        console.log("onBeforeMount",document.getElementById("hi"))
      })

      return{
        ...toRefs(data)
      }
    }
  }
</script>

打开我们的浏览器在控制台中是这样显示的: image-20230305095652373.png onBeforeMount之所以显示的是null是因为,执行它的时候页面还没有渲染,此时html里面的语句是都还没有渲染的,整个html都为null。

onBeforeUpdate

DOM更新之前

onUpdated

DOM跟新之后

我们来看个案例:

我们在刚刚的setup()方法中再增加以下代码

setTimeout(()=>{
  data.msg="hey"
},2000);
      //DOM更新前
      onBeforeUpdate(()=>{
        console.log("onBeforeUpdate",document.getElementById("hi"))
      })
      //DOM更新后
      onUpdated(()=>{
        console.log("onUpdated",document.getElementById("hi"))
      })
      

过两秒之后控制台输出了onbeforeUpdate和onUpdated image-20230305102424076.png

beforeDestroy

页面销毁之前

destroyed

页面销毁之后

Vue3事件绑定(一部分)

(1) v-model:双向绑定

当我们在input输入框中使用双向绑定,当我们改变input框中的内容时,setup()方法中对应的响应式数据也会发生改变。

<input type="text" placeholder="请输入您的姓名" v-model="username"/>
<textarea cols="30" rows="10" placeholder="请输入您的简介" v-model="userInput"></textarea>
<p>{{username}}------{{userInput}}</p>

比如此时我们绑定了姓名和个人简介,此时就会出现以下效果,在输入框内容改变的同时,我们获取绑定的数据也显示了出来,可见我们的双向绑定是成功的。 image-20230305112212630.png (2) input:输入事件 blur:失去焦点 focus:获取焦点 change:内容更改。

input事件就是在我们输入时会监听我们输入的事件。

focus是在我们选定input框时会发生的事件。

blur是我们在选定后又没有选定后发生的事件。

例如我们在原来基础上加了个手机号的输入框

<input type="text" placeholder="请输入您的手机号" v-model="userPhone"
@focus="handleFocus" @blur="handleBlur" @input="handleInput" />

当我们选定输入框时,我们在控制台打印了获取焦点的内容。 image-20230305113228373.png 此时我们又不选定输入框(注意此时输入框边框颜色变浅,说明又没有选定输入框),控制台又输出了失去焦点的内容。 image-20230305113533641.png 我们又在输入框中用@input方法校验手机号是否正确(适用于实时查询,每输入一个字符都会触发该事件),我们可以观察到手机号不正确打印了10次,第11次的时候显示了手机号正确。因为@input方法是实时监控的,当你每改变输入框的内容都会触发事件,所以当你输入前10个数字的时候,每输入一次都会触发事件,而又不符合手机号的规范所以输出了10次不正确,当你输入第11个数字的时候,这时候整个11个数字为正确的手机号,于是输出了手机号正确。

image-20230305114051385.png (3) v-on:事件名 绑定事件 如 v-on:click = "handleClick" 也可简化为 @click = "handleClick"

<button @click="submit">提交</button>

比如我们输入了我们的姓名手机号和个人简介后要提交数据,我们就把提交的事件设置为点击事件,并在点击后alert一个提交的数据。 image-20230305114658546.png (4)当然还有很多其他的事件比如v-show ,v-if 还有input中的@keyup.enter和@change等事件都可以尝试尝试。

HTML部分

<input type="text" placeholder="请输入您的姓名" v-model="username"/>
<input type="text" placeholder="请输入您的手机号" v-model="userPhone"
    @focus="handleFocus" @blur="handleBlur" @input="handleInput" />
    <textarea cols="30" rows="10" placeholder="请输入您的简介" v-model="userInput"></textarea>
    <button @click="submit">提交</button>
    <p>{{username}}------{{userInput}}</p>

JS部分

setup(){
  const data = reactive({
    msg:"hello",
    username:"",
    userInput:"",
    userPhone:"",
  })
  const submit = ()=>{
    alert("提交成功"+`${data.username}的个人简介是${data.userInput}`)
  }
  const handleFocus = ()=>{
    console.log("获取焦点")
  }
  const handleBlur = ()=>{
    if (!data.userPhone){
      alert("手机号为必填!!!")
    }
  }
  const handleInput = ()=>{
    if (!/^1[3,4,5,7,8,9][0-9]{9}$/.test(data.userPhone)){
      console.log("手机号不正确")
    }else {
      console.log("手机号正确")
    }
  }
  return{
        submit,
        handleFocus,
        handleBlur,
        handleInput,
        ...toRefs(data)
      }
    }
  }

路由配置

1、路由配置有两种模式,一种是hash模式,还有一种是history模式。它们的区别是:

(1)在url的外观上hash模式会有一个#号,而路由模式没有。

(2)在我们刷新的时候,hash会直接记载到地址栏对应的界面,而history刷新浏览器会重新向服务器发送请求,如果没有匹配当前url,就会出现404页面。

(3)hash可以兼容IE8,history能兼容IE10。

2、组件引入有两种方式,一种是在头部直接import引入,还有一种是用component: ()=>import('url')的方式引入。这两种引入方式的区别是:在头部引入时会在项目启动时就加载页面,而在component中引入是一种懒加载,即进入页面时才会加载代码。在大型项目中,当你的页面非常多的时候我们推荐懒加载,这样可以提高我们的性能。

import { createRouter, createWebHashHistory,createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const routes = [
  {
    path: '/',			//页面路径
    name: 'home',		//页面name
    component: HomeView //当前路由对应的组件
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    //告诉我们component是懒加载模式
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  },
  {
    path: '/login',
    name: 'login',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/LoginView')
  }
]
const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

在App.vue中

<template>
  <nav>
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link>
  </nav>
  <router-view/>
</template>

router-link相当于a标签 to 相当于路由的path路径,to里面的内容就是对应path中的内容。router-view就是展示路由对应的组件的内容。

有几个router-view对应的组件就会被展现几次。

嵌套路由

我们可以在路由下面嵌套路由(也叫子路由),例如:

{
  path: '/',
  name:'layout',
  component: ()=>import('../views/LayOut/LayOut'),
  //	子路由/嵌套路由
  children:[
    {
      path:'/index',
      name:'index',
      component:()=>import('../views/pages/rolesList')
    },
    {
      path:'/user',
      name:'user',
      component:()=>import('../views/pages/userList')
    }
  ]

}

这样做的好处

(1)我们可以多次复用父路由的页面,精简我们的代码,提高我们的开发效率。

(2)在例如后台管理界面中我们侧边栏有多个选项时可以方便我们进行路由跳转。