目录
1、setup函数
setup函数从组件生命周期来看,在beforeCreate之前执行
vue2中的函数this指向vue组件实例,但是vue3中的this是undefined,所以在vue3的项目中几乎不用this,所有的东西都是在函数中返回
如果数据在函数或者模板中使用,需要在setup中返回
2、ref函数
通常使用它定义响应式数据,不限类型
<template>
<div>
<button @click="toggle">显示隐藏图片</button>
<img v-show="show" src="./assets/logo.png" alt="" />
{{ number }}
<button @click="addFn">+1</button>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const show = ref(true)
const number = ref(0)
const toggle = () => {
show.value = !show.value
}
const addFn = () => {
number.value++
}
return { show, toggle, number, addFn }
},
}
</script>
<style>
div {
width: 300px;
height: 300px;
}
</style>
3、ractive响应式
vue2中data函数返回对象数据是响应式的,但是setup中返回的对象数据不是响应式的就需要使用reactive转成响应式
<template>
<div>{{ obj.name }}---{{ obj.age }}</div>
</template>
<script>
import { reactive } from 'vue'
export default {
setup() {
const obj = reactive({ name: '小明', age: 20 })
return {obj}
},
}
</script>
4、ref和reactive的区别
1)reactive可以转换对象成为响应式数据对象,但是不支持简单数据类型
2)ref可以转换简单数据类型为响应式数据对象,也支持复杂数据类型,使用的时候需要加上.value
推荐用法::
如果能确定数据是对象且字段名称也确定,可以使用reactive转成响应式数据,其他一般使用ref
5、setup语法糖
一般写法:
<script>
export default {
setup() {
const say = () => console.log('hi')
return { say }
}
}
</script>
语法糖写法:
<script setup>
const say = () => console.log('hi')
</script>
6、computed函数
所有引用的函数都需要从vue中导出
使用场景:当需要依赖一个数据得到新的数据使用计算属性
<template>
<div>{{ obj.name }}---{{ obj.age }}</div>
<div>{{ hig }}</div>
</template>
<script setup>
import { computed, reactive, ref } from 'vue'
const obj = reactive({ name: '小明', age: 20 })
const score = ref([1, 2, 3])
const hig = computed(() => score.value.filter((item) => item >= 2))
</script>
7、watch函数
1、监听一个数据变化
<div>{{ count }}</div>
const count = ref(0)
watch(count, () => {
console.log('count数量发生改变了')
})
2、监听多个数据变化
使用 [ ] 将需要监听的数据放进去
const count = ref(0)
const obj = reactive({ name: '小明', age: 20 })
setTimeout(() => {
count.value++
obj.age++
}, 1000)
watch([count, obj], () => {
console.log('count数量发生改变了')
console.log('obj的age发生了改变')
})
监听响应式数据中的一个数据
watch(
() => obj.age,
() => {
console.log('obj.name发生了变化')
}
)
配置深度监听
watch(
() => obj.name,
() => {
console.log("数据改变了");
},
{
// 开启深度监听
deep: true,
+ // 默认执行一次
+ immediate: true
}
);
8、生命周期函数对比
9、使用ref获取dom
<script setup>
import { ref } from 'vue'
const hRef = ref(null)
const clickFn = () => {
hRef.value.innerText = '我不是标题'
}
</script>
<template>
<div>
<h1 ref="hRef">我是标题</h1>
<button @click="clickFn">操作DOM</button>
</div>
</template>
10、处理响应式数据 toRef
- 解构响应式数据时数据不是响应式时
- 使用
toRefs
处理响应式数据 - 作用:把对象中的每一个属性做一次包装成为响应式数据
- 响应式数据展开的时候使用,解构响应式数据的时候使用
- 当去解构和展开响应式数据对象使用
toRefs
保持响应式
import { reactive, toRefs } from "vue";
const user = reactive({ name: "tom", age: 18 });
const { name, age } = toRefs(user)