vue3学习补漏小结

109 阅读1分钟

v-指令

v-memo

可以优化渲染能力,缩短渲染时间ms(一般需要搭配v-for使用)

v-on修饰符

冒泡案列(可以避免父组件与子组件点击冲突)

<template>
  <view @click="parent">
    <view @click.stop="child">child</view>
  </view>
</template>
<script setup lang="ts">
const child = () => {
  console.log('child');
}
const parent = () => {
  console.log('parent');
}
</script>

阻止表单提交案例

<template>
  <form action="/">
    <button @click.prevent="submit" type="submit">submit</button>
  </form>
</template>
 
 
<script setup lang="ts">
const submit = () => {
  console.log('child');
}
</script>

v-once

仅渲染元素与组件一次,并跳过之后的更新

v-for插入DOM元素

<template>
 <view v-for="item in arr">
     {{item}}
 <view>
</template>
 
 
<script setup lang="ts">
    const arr:string[]=['A','B','C','D']
    arr.splice(2,0,'DDD')
</script>

最长递增子序列算法

一列数组,当前数值与前面的数组的值比较,有大于前面数组值的在最大的索引值加1(默认为1),否则为(1)

Ref全家桶

ref

接受一个内部值并返回一个响应式且可变的 ref 对象。ref 对象仅有一个 .value property,指向该内部值。(数据和视图都会更新)

isRef

判断是不是一个ref对象

shallowRef

创建一个跟踪自身 .value 变化的 ref,但不会使其值也变成响应式的(数据改变,但是视图不会更新)

triggerRef 

强制更新页面DOM

customRef

自定义ref 

customRef 是个工厂函数要求我们返回一个对象 并且实现 get 和 set  适合去做防抖之类的

<template>
 
  <view ref="div">小满Ref</view>
  <hr>
  <view>
    {{ name }}
  </view>
  <hr>
  <button @click="change">修改 customRef</button>
 
</template>
 
<script setup lang='ts'>
import { ref, reactive, onMounted, shallowRef, customRef } from 'vue'
 
function myRef<T = any>(value: T) {
  let timer:any;
  return customRef((track, trigger) => {
    return {
      get() {
        track()
        return value
      },
      set(newVal) {
        clearTimeout(timer)
        timer =  setTimeout(() => {
          console.log('触发了set')
          value = newVal
          trigger()
        },500)
      }
    }
  })
}
 
 
const name = myRef<string>('小满')
 
 
const change = () => {
  name.value = '大满'
}
 
</script>
<style scoped>
</style>

父传值给子组件

父组件

<template>
	<nb-nav-ding title="购物车"></nb-nav-ding>
	<scroll-view>
		<shoppingCard v-for="item in carList" :item="item"></shoppingCard>//父组件传递数据到子组件
	</scroll-view>
</template>
<script lang="ts" setup>
	import {
		ref,
	} from "vue";
	import shoppingCard from './shoppingCard' //导入子组件

	//父组件获取的数据
	const carList = ref([{
			shop: '宝格丽官方',
			Discount: [{
					id: 1,
					Number: '10',
					startTime: '2022.12.01 00:00',
					endTime: '2022.12.05 22:00',
					satisfy: '1000'
				},
			],
			detail: [{
					id: 123,
					name: '宝格丽大吉岭',
					price: '589',
					describe: '大吉岭茶原版',
					photo: 'https://img0.baidu.com/it/u=3203342422,951481652&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
					count: '10',
				},
			]
		},
	])
	
</script>

子组件

<script lang="ts" setup>
	//接收父组件的值
	const prop = defineProps({
		item: Object
	})
</script>