【vue3】-【setup】-【ref()】-【reactive()】-【computed】-【watch】-【props】-【生命周期】-【自定义hook】-【路由】

创建vue3工程

在终端输入以下命令,根据自己的需求做出相应的选择:
在这里插入图片描述
生成的项目文件作用:

extensions.json:插件
favicon.ico:页签图标
env.d.ts:ts不认识.css .html .txt .js……文件,这个文件里面指定的vite/client中就是让ts认识这些文件
index.html:入口文件
vite.config.ts:TS的配置文件

setup概述

setup()beforecreate()前被执行

<template>
	<h1>一个人的信息</h1>
	<h2>姓名:{{name}}</h2>
	<h2>年龄:{{age}}</h2>
	<h2>性别:{{sex}}</h2>
  <!-- vue2和vue3中的配置冲突时,以vue3为主 -->
	<h2>a的值是:{{a}}</h2>
	<button @click="sayHello">说话(Vue3所配置的——sayHello)</button>
	<br>
	<br>
	<button @click="sayWelcome">说话(Vue2所配置的——sayWelcome)</button>
	<br>
	<br>
	<button @click="test1">测试一下在Vue2的配置中去读取Vue3中的数据、方法</button>
	<br>
	<br>
	<button @click="test2">测试一下在Vue3的setup配置中去读取Vue2中的数据、方法</button>

</template>

<script>
	// import {h} from 'vue'
	export default {
		name: 'App',
    	//vue2的配置方法也可以用,vue3向下兼容
		data() {
			return {
				sex:'男',
				a:100
			}
		},
		methods: {
			sayWelcome(){
				alert('欢迎来到尚硅谷学习')
			},
      		//vue2中可以读取vue3中的配置
			test1(){
				console.log(this.sex)
				console.log(this.name)
				console.log(this.age)
				console.log(this.sayHello)
			}
		},
		//此处只是测试一下setup,暂时不考虑响应式的问题。
		setup(){
			//数据
			let name = '张三'
			let age = 18
			let a = 200

			//方法
			function sayHello(){
				alert(`我叫${name},我${age}岁了,你好啊!`)
			}
			function test2(){
				console.log(name)
				console.log(age)
				console.log(sayHello)
        		//vue3中读不出来vue2的配置,建议这两个版本的配置不要混用
				console.log(this.sex)
				console.log(this.sayWelcome)
			}

			//返回一个对象(常用)
			return {
				name,
				age,
				sayHello,
				test2,
				a
			}

			//返回一个函数(渲染函数)
      		/*
      		渲染函数:要返回h函数的返回值
      		h('要把什么元素放到页面','标签体内容')
      		你模板中写的啥已经不重要了,页面展示以渲染函数为主
       		*/
			// return ()=> h('h1','尚硅谷')
			// 把你想展示的内容直接展示返回出去,你模板中写的啥已经不重要了,页面展示以渲染函数为主
			// return ()=> '尚硅谷'
		}
	}
</script>

setup的语法糖

setup()每次都要返回一个对象才能让<template></template>使用,于是vue3提供了语法糖<script setup>这里面直接写原setup()方法中的代码即可</script>来改善这一现象:

<script>
	// import {h} from 'vue'
	export default {
		name: 'App'// 指定该组件的名字
	}
</script>
<!--如果你不写上面那个script标签,组件名会取.vue文件名-->
<script setup>
	//数据
	let name = '张三'
	let age = 18
	let a = 200

	//方法
	function sayHello(){
		alert(`我叫${name},我${age}岁了,你好啊!`)
	}
	function test2(){
		console.log(name)
		console.log(age)
		console.log(sayHello)
        //vue3中读不出来vue2的配置,建议这两个版本的配置不要混用
		console.log(this.sex)
		console.log(this.sayWelcome)
	}
</script>

那这样又会出现另一个问题:有两个<script>标签,我们可以使用如下插件
在这里插入图片描述
并在vite.config.ts中引入插件
在这里插入图片描述
将代码优化为:

<script setup name="组件名(英文)">
	//数据
	let name = '张三'
	let age = 18
	let a = 200

	//方法
	function sayHello(){
		alert(`我叫${name},我${age}岁了,你好啊!`)
	}
	function test2(){
		console.log(name)
		console.log(age)
		console.log(sayHello)
        //vue3中读不出来vue2的配置,建议这两个版本的配置不要混用
		console.log(this.sex)
		console.log(this.sayWelcome)
	}
</script>

ref()创建响应式数据

一、vue3使用ref()reactive()让数据变成响应式数据,其中,ref()既可以定义基本类型的响应式数据,还可以定义对象类型的响应式数据,而reactive()只能定义对象类型的响应式数据

ref()底层实现:

  1. 基本类型的数据:响应式依然是靠Object.defineProperty()getset完成的。
  2. 对象类型的数据:内部 “ 求助 ” 了Vue3.0中的一个新函数—— reactive函数。

二、语法:const xxx = ref(initValue),如:let name = ref('张三'),把数据使用ref(数据)包一下,数据就变成响应式的了。ref()把’张三’加工一下,加工成了个引用实现(RefImpl)的实例对象,然后存在name中。

如果ref(数据)包裹的数据是一个对象,对象中的每个属性都是响应式的,哪怕对象中的是对象,对象里的对象的每个属性也都是响应式的

三、JS中操作这个响应式数据: xxx.value,即在setup中使用时,本例需要通过name.value获取数据。

xxx.value得到的是由ref函数包裹的数据,如果ref(数据)包裹的数据是一个对象,那么在setup中使用时,需要通过对象.value.键名获取数据。

四、模板中读取数据:不需要.value,直接:<div>{{xxx}}</div>。本例在模板中使用时,还是使用name,模板发现name是RefImpl的实例对象,会自己去读取他的value属性。

<template>
	<h1>一个人的信息</h1>
	<h2>姓名:{{name}}</h2>
	<h2>年龄:{{age}}</h2>
	<h3>工作种类:{{job.type}}</h3>
	<h3>工作薪水:{{job.salary}}</h3>
	<button @click="changeInfo">修改人的信息</button>
	<ul>
      <li v-for="g in games" :key="g.id">{{ g.name }}</li>
    </ul>
	<button @click="changeFirstGame">修改第一游戏</button>
</template>

<script>
	import {ref} from 'vue'// 引入ref
	export default {
		name: 'App',
		setup(){
			// 数据
			let name = ref('张三')
			let age = ref(18)
			let job = ref({
				type:'前端工程师',
				salary:'30K'
			})
			let games = ref([
  				{ id: 'ahsgdyfa01', name: '英雄联盟' },
  				{ id: 'ahsgdyfa02', name: '王者荣耀' },
  				{ id: 'ahsgdyfa03', name: '原神' }
			])
			//方法
			function changeInfo(){
        		// console.log(name,age)// 都是RefImpl实例对象,数据保存在实例对象的value属性中
				// name.value = '李四'
				// age.value = 48
				console.log(job.value)
        		/*
        		job.value得到的是由ref函数包裹的数据,此处是个对象:
        		{
					type:'前端工程师',
					salary:'30K'
			  	}
			  	所以要像下面这样更改他们的值
         		*/
				// job.value.type = 'UI设计师'
				// job.value.salary = '60K'
			}
			function changeFirstGame() {
				// games是一个数组,games.value获取到的就是这个数组
  				games.value[0].name = '流星蝴蝶剑'
			}
			//返回一个对象(常用)
			return {
				name,
				age,
				job,
				changeInfo,
				changeFirstGame,
				games 
			}
		}
	}
</script>

reactive()创建(对象类型的)响应式数据

一、作用:定义一个响应式对象
二、语法:let 响应式对象= reactive(源对象)
三、返回值:一个Proxy的实例对象,简称:响应式对象。
四、注意点:reactive定义的响应式数据是“深层次”的。

<template>
  <div class="person">
    <h2>汽车信息:一台{{ car.brand }}汽车,价值{{ car.price }}万</h2>
    <h2>游戏列表:</h2>
    <ul>
      <li v-for="g in games" :key="g.id">{{ g.name }}</li>
    </ul>
    <h2>测试:{{obj.a.b.c.d}}</h2>
    <button @click="changeCarPrice">修改汽车价格</button>
    <button @click="changeFirstGame">修改第一游戏</button>
    <button @click="test">测试</button>
  </div>
</template>

<script lang="ts" setup name="Person">
import { reactive } from 'vue'// 引入reactive

// 数据
let car = reactive({ brand: '奔驰', price: 100 })
let games = reactive([
  { id: 'ahsgdyfa01', name: '英雄联盟' },
  { id: 'ahsgdyfa02', name: '王者荣耀' },
  { id: 'ahsgdyfa03', name: '原神' }
])
let obj = reactive({
  a:{
    b:{
      c:{
        d:666
      }
    }
  }
})

function changeCarPrice() {
  car.price += 10
}
function changeFirstGame() {
  games[0].name = '流星蝴蝶剑'
}
function test(){
  obj.a.b.c.d = 999
}
</script>

ref对比reactive

一、ref创建的变量必须使用.value(可以使用volar插件自动添加.value)。
在这里插入图片描述
二、reactive重新分配一个新对象,会失去响应式(可以使用Object.assign去整体替换)。

<template>
  <div class="person">
    <h2>汽车信息:一辆{{car.brand}}车,价值{{car.price}}万</h2>
    <button @click="changeBrand">修改汽车的品牌</button>
    <button @click="changePrice">修改汽车的价格</button>
    <button @click="changeCar">修改汽车</button>
    <hr>
    <h2>当前求和为:{{sum}}</h2>
    <button @click="changeSum">点我sum+1</button>
  </div>
</template>

<script lang="ts" setup name="Person">
  import {ref,reactive} from 'vue'

  // 数据
  let car = reactive({brand:'奔驰',price:100})
  let sum = ref(0)

  // 方法
  function changeBrand(){
    car.brand = '宝马'
  }
  function changePrice(){
    car.price += 10
  }
  function changeCar(){
    // reactive重新分配一个新对象,会失去响应式
    // car = {brand:'奥拓',price:1} //这么写页面不更新的
    // car = reactive({brand:'奥拓',price:1}) //这么写页面不更新的

	// 使用Object.assign去整体替换:Object.assign(obj1,obj2,obj3,...),把obj2、obj3中的数据,每一组键值对都加在obj1中
    // 下面这个写法页面可以更新
    Object.assign(car,{brand:'奥拓',price:1})
  }
  function changeSum(){
    // sum = ref(9) //这么写页面不更新的,操作ref创建的响应式数据必须加.value才行
    sum.value += 1
  }
</script>

三、使用原则:

  1. 若需要一个基本类型的响应式数据,必须使用ref
  2. 若需要一个响应式对象,层级不深,refreactive都可以。
  3. 若需要一个响应式对象,且层级较深,推荐使用reactive

computed计算属性

<template>
  <div class="person">
    姓:<input type="text" v-model="firstName"> <br>
    名:<input type="text" v-model="lastName"> <br>
    <button @click="changeFullName">将全名改为li-si</button> <br>
    全名:<span>{{fullName}}</span> <br>
    全名:<span>{{fullName}}</span> <br>
    全名:<span>{{fullName}}</span> <br>
    全名:<span>{{fullName}}</span> <br>
    全名:<span>{{fullName}}</span> <br>
    全名:<span>{{fullName}}</span> <br>
  </div>
</template>

<script lang="ts" setup name="Person">
  import {ref,computed} from 'vue'

  let firstName = ref('zhang')
  let lastName = ref('san')

  // 这样写fullName是一个计算属性,且是只读的
  /* let fullName = computed(()=>{
    console.log(1)
    return firstName.value.slice(0,1).toUpperCase() + firstName.value.slice(1) + '-' + lastName.value
  }) */

  // 这样写fullName是一个计算属性,可读可写
  let fullName = computed({
    // 当fullName被读取时,get调用
    get(){
      return firstName.value.slice(0,1).toUpperCase() + firstName.value.slice(1) + '-' + lastName.value
    },
    // 当fullName被修改时,set调用,val是收到的修改后的值
    set(val){
      const [str1,str2] = val.split('-')
      firstName.value = str1
      lastName.value = str2
    }
  })

  function changeFullName(){
    fullName.value = 'li-si'
  }
</script>

watch监视

watch作用:监视数据的变化,但是在Vue3watch只能监视以下四种数据

  1. ref定义的数据。
  2. reactive定义的数据。
  3. 函数返回一个值(getter函数)。
  4. 一个包含上述内容的数组。

我们在Vue3中使用watch的时候,通常会遇到以下几种情况:

情况一

监视ref定义的【基本类型】数据:直接写数据名即可,监视的是其value值的改变。

<template>
  <div class="person">
    <h1>情况一:监视【ref】定义的【基本类型】数据</h1>
    <h2>当前求和为:{{sum}}</h2>
    <button @click="changeSum">点我sum+1</button>
  </div>
</template>

<script lang="ts" setup name="Person">
  import {ref,watch} from 'vue'
  // 数据
  let sum = ref(0)
  // 方法
  function changeSum(){
    sum.value += 1
  }
  // 监视,情况一:监视【ref】定义的【基本类型】数据
  // const stopWatch = watch(监视的变量,(新值,旧值)=>{}),watch函数的返回值是一个函数,调用该函数可停止对该变量的监视
  // 监视sum的变化,当sum的值>=10时,不再监视sum的改变
  const stopWatch = watch(sum,(newValue,oldValue)=>{
    console.log('sum变化了',newValue,oldValue)
    if(newValue >= 10){
      stopWatch()
    }
  })
</script>

情况二

监视ref定义的【对象类型】数据:直接写数据名,监视的是对象的【地址值】,若想监视对象内部的数据,要手动开启深度监视。注意:

  1. 若修改的是ref定义的对象中的属性,newValueoldValue 都是新值,因为它们是同一个对象,地址值没变。
  2. 若修改整个ref定义的对象,newValue 是新值, oldValue 是旧值,因为不是同一个对象了。
<template>
  <div class="person">
    <h1>情况二:监视【ref】定义的【对象类型】数据</h1>
    <h2>姓名:{{ person.name }}</h2>
    <h2>年龄:{{ person.age }}</h2>
    <button @click="changeName">修改名字</button>
    <button @click="changeAge">修改年龄</button>
    <button @click="changePerson">修改整个人</button>
  </div>
</template>

<script lang="ts" setup name="Person">
  import {ref,watch} from 'vue'
  // 数据
  let person = ref({
    name:'张三',
    age:18
  })
  // 方法
  function changeName(){
    person.value.name += '~'
  }
  function changeAge(){
    person.value.age += 1
  }
  function changePerson(){
    person.value = {name:'李四',age:90}
  }
  /* 
    监视【ref】定义的【对象类型】数据,监视的是对象的地址值,若想监视对象内部属性的变化,需要手动开启深度监视:deep:true
    watch的第一个参数是:被监视的数据
    watch的第二个参数是:监视的回调
    watch的第三个参数是:配置对象(deep、immediate等等.....) ,immediate:true表示立即执行该监视函数
  */
  watch(person,(newValue,oldValue)=>{
    console.log('person变化了',newValue,oldValue)
  },{deep:true,immediate:true})
</script>

情况三

监视reactive定义的【对象类型】数据,且默认开启了深度监视。

<template>
  <div class="person">
    <h1>情况三:监视【reactive】定义的【对象类型】数据</h1>
    <h2>姓名:{{ person.name }}</h2>
    <h2>年龄:{{ person.age }}</h2>
    <button @click="changeName">修改名字</button>
    <button @click="changeAge">修改年龄</button>
    <button @click="changePerson">修改整个人</button>
    <hr>
    <h2>测试:{{obj.a.b.c}}</h2>
    <button @click="test">修改obj.a.b.c</button>
  </div>
</template>

<script lang="ts" setup name="Person">
  import {reactive,watch} from 'vue'
  // 数据
  let person = reactive({
    name:'张三',
    age:18
  })
  let obj = reactive({
    a:{
      b:{
        c:666
      }
    }
  })
  // 方法
  function changeName(){
    person.name += '~'
  }
  function changeAge(){
    person.age += 1
  }
  function changePerson(){
    Object.assign(person,{name:'李四',age:80})
  }
  function test(){
    obj.a.b.c = 888
  }

  // 监视,情况三:监视【reactive】定义的【对象类型】数据,且默认是开启深度监视的,这种深度监视是不能关闭的
  watch(person,(newValue,oldValue)=>{
    console.log('person变化了',newValue,oldValue)
  })
  watch(obj,(newValue,oldValue)=>{
    console.log('Obj变化了',newValue,oldValue)
  })
</script>

情况四

监视refreactive定义的【对象类型】数据中的某个属性,注意点如下:

  1. 若该属性值不是【对象类型】,需要写成函数形式。
  2. 若该属性值是依然是【对象类型】,可直接编,也可写成函数,建议写成函数。

结论:监视的要是对象里的属性,那么最好写函数式,注意点:若是对象监视的是地址值,需要关注对象内部,需要手动开启深度监视。

<template>
  <div class="person">
    <h1>情况四:监视【ref】或【reactive】定义的【对象类型】数据中的某个属性</h1>
    <h2>姓名:{{ person.name }}</h2>
    <h2>年龄:{{ person.age }}</h2>
    <h2>汽车:{{ person.car.c1 }}、{{ person.car.c2 }}</h2>
    <button @click="changeName">修改名字</button>
    <button @click="changeAge">修改年龄</button>
    <button @click="changeC1">修改第一台车</button>
    <button @click="changeC2">修改第二台车</button>
    <button @click="changeCar">修改整个车</button>
  </div>
</template>

<script lang="ts" setup name="Person">
  import {reactive,watch} from 'vue'

  // 数据
  let person = reactive({
    name:'张三',
    age:18,
    car:{
      c1:'奔驰',
      c2:'宝马'
    }
  })
  // 方法
  function changeName(){
    person.name += '~'
  }
  function changeAge(){
    person.age += 1
  }
  function changeC1(){
    person.car.c1 = '奥迪'
  }
  function changeC2(){
    person.car.c2 = '大众'
  }
  function changeCar(){
    person.car = {c1:'雅迪',c2:'爱玛'}
  }

  // 监视,情况四:监视响应式对象中的某个属性,且该属性是基本类型的,要写成函数式
  /* watch(()=> person.name,(newValue,oldValue)=>{
    console.log('person.name变化了',newValue,oldValue)
  }) */

  // 监视,情况四:监视响应式对象中的某个属性,且该属性是对象类型的,可以直接写,也能写函数,更推荐写函数
  watch(()=>person.car,(newValue,oldValue)=>{
    console.log('person.car变化了',newValue,oldValue)
  },{deep:true})
</script>

情况五

监视上述的多个数据

<template>
  <div class="person">
    <h1>情况五:监视上述的多个数据</h1>
    <h2>姓名:{{ person.name }}</h2>
    <h2>年龄:{{ person.age }}</h2>
    <h2>汽车:{{ person.car.c1 }}、{{ person.car.c2 }}</h2>
    <button @click="changeName">修改名字</button>
    <button @click="changeAge">修改年龄</button>
    <button @click="changeC1">修改第一台车</button>
    <button @click="changeC2">修改第二台车</button>
    <button @click="changeCar">修改整个车</button>
  </div>
</template>

<script lang="ts" setup name="Person">
  import {reactive,watch} from 'vue'

  // 数据
  let person = reactive({
    name:'张三',
    age:18,
    car:{
      c1:'奔驰',
      c2:'宝马'
    }
  })
  // 方法
  function changeName(){
    person.name += '~'
  }
  function changeAge(){
    person.age += 1
  }
  function changeC1(){
    person.car.c1 = '奥迪'
  }
  function changeC2(){
    person.car.c2 = '大众'
  }
  function changeCar(){
    person.car = {c1:'雅迪',c2:'爱玛'}
  }

  // 监视,情况五:监视上述的多个数据。watch的第一个参数接受一个数组,数组是一个函数,函数的返回值就是要监视的值
  watch([()=>person.name,person.car],(newValue,oldValue)=>{
    console.log('person.car变化了',newValue,oldValue)
  },{deep:true})
</script>

watchEffect

一、官网定义:立即运行一个函数,同时响应式地追踪其依赖,并在依赖更改时重新执行该函数。
二、watch对比watchEffect

  1. 都能监听响应式数据的变化,不同的是监听数据变化的方式不同
  2. watch:要明确指出监视的数据
  3. watchEffect:不用明确指出监视的数据(函数中用到哪些属性,那就监视哪些属性)。
 <template>
    <div class="person">
      <h1>需求:水温达到50℃,或水位达到20cm,则联系服务器</h1>
      <h2 id="demo">水温:{{temp}}</h2>
      <h2>水位:{{height}}</h2>
      <button @click="changePrice">水温+1</button>
      <button @click="changeSum">水位+10</button>
    </div>
  </template>
  
  <script lang="ts" setup name="Person">
    import {ref,watch,watchEffect} from 'vue'
    // 数据
    let temp = ref(0)
    let height = ref(0)
  
    // 方法
    function changePrice(){
      temp.value += 10
    }
    function changeSum(){
      height.value += 1
    }
  
    // 用watch实现,需要明确的指出要监视:temp、height
    watch([temp,height],(value)=>{
      // 从value中获取最新的temp值、height值
      const [newTemp,newHeight] = value
      // 室温达到50℃,或水位达到20cm,立刻联系服务器
      if(newTemp >= 50 || newHeight >= 20){
        console.log('联系服务器')
      }
    })
  
    // 用watchEffect实现,不用指明具体要监视的数据。watchEffect接收一个函数,他会自动监视该函数中用到的值,只要这个函数用到的值发生了变化,就会立即执行这个函数
    const stopWtach = watchEffect(()=>{
      // 室温达到50℃,或水位达到20cm,立刻联系服务器
      if(temp.value >= 50 || height.value >= 20){
        console.log(document.getElementById('demo')?.innerText)
        console.log('联系服务器')
      }
      // 水温达到100,或水位达到50,取消监视
      if(temp.value === 100 || height.value === 50){
        console.log('清理了')
        stopWtach()
      }
    })
</script>

标签的ref属性

一、作用:用于注册模板引用。

  1. 用在普通DOM标签上,获取的是DOM节点。
  2. 用在组件标签上,获取的是组件实例对象。

为什么使用ref属性获取dom或组件而不用id?
因为vue是单页面应用,可能会出现id冲突,比如说你在a.vue文件中定义了id=‘a’,并通过id获取该dom,你的同事在b.vue文件中也定义了id=‘a’,如果b.vue在a.vue之前使用,那么你通过id获取的dom可能是你同事定义的那个

二、用在普通DOM标签上:

<template>
  <div class="person">
    <h1 ref="title1">尚硅谷</h1>
    <h2 ref="title2">前端</h2>
    <h3 ref="title3">Vue</h3>
    <input type="text" ref="inpt"> <br><br>
    <button @click="showLog">点我打印内容</button>
  </div>
</template>

<script lang="ts" setup name="Person">
  import {ref} from 'vue'
  // 创建相应的ref容器,用于存储ref标记的内容。变量名即容器名和模版中指定的ref的属性值必须保持一致,才是创建了相应的ref容器
  let title1 = ref()// 创建title1的ref容器,这个title1得和模板中ref="title1"的title1一致,下同
  let title2 = ref()
  let title3 = ref()

  function showLog(){
    // 通过id获取元素
    const t1 = document.getElementById('title1')
    // 打印内容
    console.log((t1 as HTMLElement).innerText)
    console.log((<HTMLElement>t1).innerText)
    console.log(t1?.innerText)
    
		/************************************/
		
    // 通过ref获取元素:相应的ref容器.value
    console.log(title1.value)
    console.log(title2.value)
    console.log(title3.value)
  }
</script>

三、用在组件标签上:

<!-- 父组件App.vue -->
<template>
  <Person ref="ren"/>
  <button @click="test">测试</button>
</template>

<script lang="ts" setup name="App">
  import Person from './components/Person.vue'
  import {ref} from 'vue'

  let ren = ref()

  function test(){
    console.log(ren.value.name)
    console.log(ren.value.age)
  }
</script>


<!-- 子组件Person.vue中要使用defineExpose暴露内容 -->
<script lang="ts" setup name="Person">
  import {ref,defineExpose} from 'vue'
	// 数据
  let name = ref('张三')
  let age = ref(18)
  // 使用defineExpose将组件中的数据交给外部
  defineExpose({name,age})
</script>

ts中的接口、泛型、自定义类型

props

用于父组件向子组件传值

// 定义一个接口,限制每个Person对象的格式
export interface PersonInter {
  id:string,
  name:string,
  age:number
}
    
 // 定义一个自定义类型Persons,Persons是一个数组,数组中的每一项都满足PersonInter接口规范
export type Persons = Array<PersonInter>

父组件App.vue中代码:

<template>
<!-- 给子组件的list属性传值,值为父组件的persons数组 -->
 	<Person :list="persons"/>
</template>
   
<script lang="ts" setup name="App">
   import Person from './components/Person.vue'
   import {reactive} from 'vue'
   import {type Persons} from './types'// 引入Persons类型
   // persons是一个由reactive()定义的响应式数组,该数组是Persons类型,即数组中的每一项都满足PersonInter接口规范。
   // 下面这种写法就是为了约束reactive()定义的响应式数据,直接在reactive后面添加<Persons>即可
   let persons = reactive<Persons>([
      {id:'e98219e12',name:'张三',age:18},
      {id:'e98219e13',name:'李四',age:19},
      {id:'e98219e14',name:'王五',age:20}
   ])
</script>

子组件 Person.vue中代码:

<template>
 <div class="person">
  <ul>
      <li v-for="item in list" :key="item.id">
         {{item.name}}--{{item.age}}
       </li>
     </ul>
    </div>
</template>
<script lang="ts" setup name="Person">
 import {defineProps} from 'vue'
 import {type PersonInter} from '@/types'// @表示在src下
// 第一种写法:仅接收。写法:defineProps(['从父组件那里接收到的参数1','从父组件那里接收到的参数2',...])
// const props = defineProps(['list'])

// 第二种写法:接收+限制类型。写法:defineProps<{从父组件那里接收到的参数1:从父组件那里接收到的参数1的类型,从父组件那里接收到的参数2:从父组件那里接收到的参数2的类型,...}>()
// defineProps<{list:Persons}>()

// 第三种写法:接收+限制类型+指定默认值+限制必要性
// 1. 父组件可以不给子组件传list,直接在list后面添加?表示该参数非必需:list?
// 2. 使用withDefaults()指定参数的默认值,withDefaults()的第二个参数接收一个对象,你想给哪个参数指定默认值,哪个参数就是这个对象的键(本例中想要给list指定默认值,所以键是list);值是一个函数,函数的返回值是指定的默认值
let props = withDefaults(defineProps<{list?:Persons}>(),{
      list:()=>[{id:'asdasg01',name:'小猪佩奇',age:18}]
})
  
console.log(props)
</script>

生命周期

一、概念:Vue组件实例在创建时要经历一系列的初始化步骤,在此过程中Vue会在合适的时机,调用特定的函数,从而让开发者有机会在特定阶段运行自己的代码,这些特定的函数统称为:生命周期钩子
二、规律:生命周期整体分为四个阶段,分别是:创建、挂载、更新、销毁,每个阶段都有两个钩子,一前一后。
三、Vue2的生命周期

  1. 创建阶段:beforeCreatecreated
  2. 挂载阶段:beforeMountmounted
  3. 更新阶段:beforeUpdateupdated
  4. 销毁阶段:beforeDestroydestroyed

四、Vue3的生命周期

  1. 创建阶段:setup
  2. 挂载阶段:onBeforeMountonMounted
  3. 更新阶段:onBeforeUpdateonUpdated
  4. 卸载阶段:onBeforeUnmountonUnmounted

常用的钩子:onMounted(挂载完毕)、onUpdated(更新完毕)、onBeforeUnmount(卸载之前)

示例代码:

 <template>
    <div class="person">
      <h2>当前求和为:{{ sum }}</h2>
      <button @click="changeSum">点我sum+1</button>
    </div>
  </template>
  
  <!-- vue3写法 -->
  <script lang="ts" setup name="Person">
    import { 
      ref, 
      onBeforeMount, 
      onMounted, 
      onBeforeUpdate, 
      onUpdated, 
      onBeforeUnmount, 
      onUnmounted 
    } from 'vue'
  
    // 数据
    let sum = ref(0)
    // 方法
    function changeSum() {
      sum.value += 1
    }
    console.log('setup')
    // 生命周期钩子
    onBeforeMount(()=>{
      console.log('挂载之前')
    })
    onMounted(()=>{
      console.log('挂载完毕')
    })
    onBeforeUpdate(()=>{
      console.log('更新之前')
    })
    onUpdated(()=>{
      console.log('更新完毕')
    })
    onBeforeUnmount(()=>{
      console.log('卸载之前')
    })
    onUnmounted(()=>{
      console.log('卸载完毕')
    })
  </script>

自定义hook

一、什么是hook:本质是一个函数,把setup函数中使用的Composition API进行了封装,类似于vue2.x中的mixin
二、自定义hook的优势:复用代码,让setup中的逻辑更清楚易懂。
三、示例代码:
将所有和求和相关的(数据、方法、钩子等)都放在useSum.ts中并暴露出去,具体内容如下:

  import {ref,onMounted} from 'vue'
  
  export default function(){
    let sum = ref(0)
  
    const increment = ()=>{
      sum.value += 1
    }
    const decrement = ()=>{
      sum.value -= 1
    }
    onMounted(()=>{
      increment()
    })
  
    //向外部暴露数据
    return {sum,increment,decrement}
  }		

将所有和获取小狗图片相关的(数据、方法、钩子等)都放在useDog.ts中内容如下:

  import {reactive,onMounted} from 'vue'
  import axios,{AxiosError} from 'axios'
  
  export default function(){
    let dogList = reactive<string[]>([])
  
    // 方法
    async function getDog(){
      try {
        // 发请求
        let {data} = await axios.get('https://dog.ceo/api/breed/pembroke/images/random')
        // 维护数据
        dogList.push(data.message)
      } catch (error) {
        // 处理错误
        const err = <AxiosError>error
        console.log(err.message)
      }
    }
  
    // 挂载钩子
    onMounted(()=>{
      getDog()
    })
  	
    //向外部暴露数据
    return {dogList,getDog}
  }

组件中具体使用:

  <template>
    <h2>当前求和为:{{sum}}</h2>
    <button @click="increment">点我+1</button>
    <button @click="decrement">点我-1</button>
    <hr>
    <img v-for="(u,index) in dogList.urlList" :key="index" :src="(u as string)"> 
    <span v-show="dogList.isLoading">加载中......</span><br>
    <button @click="getDog">再来一只狗</button>
  </template>
  
  <script lang="ts">
    import {defineComponent} from 'vue'
  
    export default defineComponent({
      name:'App',
    })
  </script>
  
  <script setup lang="ts">
  	// 引入要用的东西
    import useSum from './hooks/useSum'
    import useDog from './hooks/useDog'
  	// 解构后直接使用
    let {sum,increment,decrement} = useSum()
    let {dogList,getDog} = useDog()
  </script>

路由

基本切换效果

路由配置文件router/index.ts代码如下:

// 创建一个路由器,并暴露出去

// 第一步:引入createRouter
import {createRouter,createWebHistory} from 'vue-router'
// 引入一个一个可能要呈现组件
import Home from '@/components/Home.vue'
import News from '@/components/News.vue'
import About from '@/components/About.vue'

// 第二步:创建路由器
const router = createRouter({
  history:createWebHistory(), //路由器的工作模式(稍后讲解)
  routes:[ //一个一个的路由规则
    {
      path:'/home',
      component:Home
    },
    {
      path:'/news',
      component:News
    },
    {
      path:'/about',
      component:About
    },
  ]
})

// 暴露出去router
export default router

main.ts代码如下:

// 引入createApp用于创建应用
import {createApp} from 'vue'
// 引入App根组件
import App from './App.vue'
// 引入路由器
import router from './router'

// 创建一个应用
const app = createApp(App)
// 使用路由器
app.use(router)
// 挂载整个应用到app容器中
app.mount('#app')

App.vue代码如下

<template>
  <div class="app">
    <h2 class="title">Vue路由测试</h2>
    <!-- 导航区 -->
    <div class="navigate">
      <!-- 
		1. 使用RouterLink标签进行路由跳转,to属性指定跳转路径,active-class指定被点击后的类名
	  -->
      <RouterLink to="/home" active-class="xiaozhupeiqi">首页</RouterLink>
      <RouterLink to="/news" active-class="xiaozhupeiqi">新闻</RouterLink>
      <RouterLink to="/about" active-class="xiaozhupeiqi">关于</RouterLink>
    </div>
    <!-- 展示区 -->
    <div class="main-content">
      <!-- RouterView标签展示路由组件 -->
      <RouterView></RouterView>
    </div>
  </div>
</template>

<script lang="ts" setup name="App">
  import {RouterView,RouterLink} from 'vue-router'
</script>

<style>
    /* App */
  .title {
    text-align: center;
    word-spacing: 5px;
    margin: 30px 0;
    height: 70px;
    line-height: 70px;
    background-image: linear-gradient(45deg, gray, white);
    border-radius: 10px;
    box-shadow: 0 0 2px;
    font-size: 30px;
  }
  .navigate {
    display: flex;
    justify-content: space-around;
    margin: 0 100px;
  }
  .navigate a {
    display: block;
    text-align: center;
    width: 90px;
    height: 40px;
    line-height: 40px;
    border-radius: 10px;
    background-color: gray;
    text-decoration: none;
    color: white;
    font-size: 18px;
    letter-spacing: 5px;
  }
  .navigate a.xiaozhupeiqi {
    background-color: #64967E;
    color: #ffc268;
    font-weight: 900;
    text-shadow: 0 0 1px black;
    font-family: 微软雅黑;
  }
  .main-content {
    margin: 0 auto;
    margin-top: 30px;
    border-radius: 10px;
    width: 90%;
    height: 400px;
    border: 1px solid;
  }
</style>

两个注意点

  1. 路由组件通常存放在pagesviews文件夹,一般组件通常存放在components文件夹。
  2. 通过点击导航,视觉效果上“消失” 了的路由组件,默认是被卸载掉的,需要的时候再去挂载

路由器工作模式

一、history模式

  1. 优点:URL更加美观,不带有#,更接近传统的网站URL
  2. 缺点:后期项目上线,需要服务端配合处理路径问题,否则刷新会有404错误。
const router = createRouter({
	history:createWebHistory(), //history模式
})

二、hash模式

  1. 优点:兼容性更好,因为不需要服务器端处理路径。
  2. 缺点:URL带有#不太美观,且在SEO优化方面相对较差。
const router = createRouter({
	history:createWebHashHistory(),//hash模式
})

to的两种写法

<!-- 第一种:to的字符串写法 -->
<router-link active-class="active" to="/home">主页</router-link>

<!-- 第二种:to的对象写法 -->
<router-link active-class="active" :to="{path:'/home'}">Home</router-link>

命名路由

一、作用:可以简化路由跳转及传参(后面就讲)。

routes:[
  {
    name:'zhuye',// 给路由规则命名
    path:'/home',
    component:Home
  },
  {
    name:'xinwen',
    path:'/news',
    component:News,
  },
  {
    name:'guanyu',
    path:'/about',
    component:About
  }
]

跳转路由:

<!--简化前:需要写完整的路径(to的字符串写法) -->
<router-link to="/news/detail">跳转</router-link>

<!--简化后:直接通过名字跳转(to的对象写法配合name属性) -->
<router-link :to="{name:'guanyu'}">跳转</router-link>

嵌套路由

一、编写News的子路由Detail.vue:在配置路由规则时,使用children配置项:

// 创建一个路由器,并暴露出去

// 第一步:引入createRouter
import {createRouter,createWebHistory,createWebHashHistory} from 'vue-router'
// 引入一个一个可能要呈现组件
import Home from '@/pages/Home.vue'
import News from '@/pages/News.vue'
import About from '@/pages/About.vue'
import Detail from '@/pages/Detail.vue'

// 第二步:创建路由器
const router = createRouter({
  history:createWebHistory(), //路由器的工作模式(稍后讲解)
  routes:[ //一个一个的路由规则
   		{
   			name:'zhuye',
   			path:'/home',
   			component:Home
   		},
   		{
   			name:'xinwen',
   			path:'/news',
   			component:News,
   			children:[// 编写News的子路由Detail.vue
   				{
   					name:'xiang',
   					path:'detail',
   					component:Detail
   				}
   			]
   		},
   		{
   			name:'guanyu',
   			path:'/about',
   			component:About
   		}
   	]
   })
   export default router

二、跳转路由(记得要加完整路径):

<router-link to="/news/detail">xxxx</router-link>
<!-- 或 -->
<router-link :to="{path:'/news/detail'}">xxxx</router-link>

三、记得去Home组件中预留一个<router-view>

<template>
     <div class="news">
       <nav class="news-list">
         <RouterLink v-for="news in newsList" :key="news.id" :to="{path:'/news/detail'}">
           {{news.name}}
         </RouterLink>
       </nav>
       <div class="news-detail">
         <RouterView/>
       </div>
     </div>
   </template>

路由传参

query参数

一、传递参数

<!-- 跳转并携带query参数(to的字符串写法) -->
<router-link to="/news/detail?a=1&b=2&content=欢迎你">跳转</router-link>
<!-- 跳转并携带query参数(to的对象写法) -->
<RouterLink :to="{
	//name:'xiang', //用name也可以跳转
    path:'/news/detail',
    query:{
    	id:news.id,
        title:news.title,
        content:news.content
	}
}">
{{news.title}}
</RouterLink>

二、接收参数:

import {useRoute} from 'vue-router'
const route = useRoute()
let {query} = toRefs(route)// 解构获取route中的query参数并使query是响应式的

三、模板中使用参数

<template>
  <ul class="news-list">
    <li>编号:{{ query.id }}</li>
    <li>标题:{{ query.title }}</li>
    <li>内容:{{ query.content }}</li>
  </ul>
</template>

params参数

一、传递params参数时,需要提前在规则中占位,router/index.ts代码如下:

// 创建一个路由器,并暴露出去

// 第一步:引入createRouter
import {createRouter,createWebHistory,createWebHashHistory} from 'vue-router'
// 引入一个一个可能要呈现组件
import Home from '@/pages/Home.vue'
import News from '@/pages/News.vue'
import About from '@/pages/About.vue'
import Detail from '@/pages/Detail.vue'

// 第二步:创建路由器
const router = createRouter({
  history:createWebHistory(), //路由器的工作模式(稍后讲解)
  routes:[ //一个一个的路由规则
    {
      name:'zhuye',
      path:'/home',
      component:Home
    },
    {
      name:'xinwen',
      path:'/news',
      component:News,
      children:[
        {
          name:'xiang',
          path:'detail/:id/:title/:content?',// 传递`params`参数时,需要提前在规则中占位。?表示这个参数可传可不传
          component:Detail
        }
      ]
    },
    {
      name:'guanyu',
      path:'/about',
      component:About
    }
  ]
})

// 暴露出去router
export default router

二、传递参数

<!-- 跳转并携带params参数(to的字符串写法) -->
<RouterLink :to="`/news/detail/001/新闻001/内容001`">{{news.title}}</RouterLink>		
      <!-- 跳转并携带params参数(to的对象写法) -->
      <RouterLink 
        :to="{// 传递params参数时,若使用to的对象写法,必须使用name配置项,不能用path。
          name:'xiang', //用name跳转
          params:{
            id:news.id,
            title:news.title,
            content:news.title
          }
        }"
      >
        {{news.title}}
      </RouterLink>

三、接收参数:

import {useRoute} from 'vue-router'
const route = useRoute()
// 打印params参数
console.log(route.params)

四、在模板中使用:

<template>
  <ul class="news-list">
    <li>编号:{{ route.params.id }}</li>
    <li>标题:{{ route.params.title }}</li>
    <li>内容:{{ route.params.content }}</li>
  </ul>
</template>

路由的props配置

一、父组件使用params传值:

<template>
  <div class="news">
    <!-- 导航区 -->
    <ul>
      <li v-for="news in newsList" :key="news.id">
        <RouterLink 
          :to="{
            name:'xiang',
            params:{
              id:news.id,
              title:news.title,
              content:news.content
            }
          }"
        >
          {{news.title}}
        </RouterLink>
      </li>
    </ul>
    <!-- 展示区 -->
    <div class="news-content">
      <RouterView></RouterView>
    </div>
  </div>
</template>

<script setup lang="ts" name="News">
  import {reactive} from 'vue'
  import {RouterView,RouterLink} from 'vue-router'

  const newsList = reactive([
    {id:'asfdtrfay01',title:'很好的抗癌食物',content:'西蓝花'},
    {id:'asfdtrfay02',title:'如何一夜暴富',content:'学IT'},
    {id:'asfdtrfay03',title:'震惊,万万没想到',content:'明天是周一'},
    {id:'asfdtrfay04',title:'好消息!好消息!',content:'快过年了'}
  ])

</script>

二、router/index.ts中配置路由时,指定将路由参数作为props传给组件

  1. props的布尔值写法:
{
	name:'xiang',
	path:'detail/:id/:title/:content',
	component:Detail,

  // props的对象写法,作用:把对象中的每一组key-value作为props传给Detail组件
  // props:{id:1,title:2,content:3}, // 数据直接传

  // props的布尔值写法,作用:把收到了每一组params参数,作为props传给Detail组件
  // 相当于:<Detail id="x" title="y" content="z"/>
  // props:true
  
  // props的函数写法,作用:把返回的对象中每一组key-value作为props传给Detail组件
  props(route){// props函数接收一个route参数,父组件传给子组件的数据都放在route.query中(也可能是route.params,可能取决于父组件怎么传的)
    return route.query
  }
}

replace属性

一、作用:控制路由跳转时操作浏览器历史记录的模式。
二、浏览器的历史记录有两种写入方式:分别为pushreplace

  1. push是追加历史记录(默认值)。
  2. replace是替换当前记录。
  3. 开启replace模式:<RouterLink replace .......>News</RouterLink>

编程式导航

一、路由组件的两个重要的属性:$route$router变成了两个hooks
二、使用router.replace()router.push()进行跳转

<template>
  <div class="news">
    <!-- 导航区 -->
    <ul>
      <li v-for="news in newsList" :key="news.id">
        <button @click="showNewsDetail(news)">查看新闻</button>
        <RouterLink 
          :to="{
            name:'xiang',
            query:{
              id:news.id,
              title:news.title,
              content:news.content
            }
          }"
        >
          {{news.title}}
        </RouterLink>
      </li>
    </ul>
    <!-- 展示区 -->
    <div class="news-content">
      <RouterView></RouterView>
    </div>
  </div>
</template>

<script setup lang="ts" name="News">
  import {reactive} from 'vue'
  import {RouterView,RouterLink,useRouter} from 'vue-router'

  const newsList = reactive([
    {id:'asfdtrfay01',title:'很好的抗癌食物',content:'西蓝花'},
    {id:'asfdtrfay02',title:'如何一夜暴富',content:'学IT'},
    {id:'asfdtrfay03',title:'震惊,万万没想到',content:'明天是周一'},
    {id:'asfdtrfay04',title:'好消息!好消息!',content:'快过年了'}
  ])

  const router = useRouter()

  interface NewsInter {
    id:string,
    title:string,
    content:string
  }

  function showNewsDetail(news:NewsInter){
    router.replace({// to的对象写法怎么写,这里就怎么写
      name:'xiang',
      query:{
        id:news.id,
        title:news.title,
        content:news.content
      }
    })
  }
onMounted(()=>{
    setTimeout(()=>{
      router.push('/news')// 编程式路由使用push
    },3000)
  }) 
</script>

重定向

一、作用:将特定的路径,重新定向到已有路由。
二、在router/index.ts中配置规则时指定,具体编码:

   {
       path:'/',
       redirect:'/about'
   }
  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值