Vue3-组合式API
setup
用法
setup函数执行机制比生命周期函数beforcreate还要早,在vue3中我们就使用不到this关键字了,在函数setup内是访问不到this的,显示的未定义
数据和函数返回
在setup中的内容使用需要return, 在里面的数据和函数,需要在最后return,才能在模板语法中使用,返回的是一个对象,里面就放我们的数据和函数
setup () {
const mes = 'curry'
const handel = () => {
console.log('库里的耳机')
}
return {
mes,
handel
}
}
语法糖
如果每条数据和函数都返回,那数据多了之后手动添加就很麻烦,我们在写逻辑代码的时候,只需要在script后面加上 setup就可以了,然后写逻辑代码的时候,直接就定义数据和函数,在模板语法中用
<script setup>
const mes = 'hello world'
const handel = () => {
console.log('库里的耳机')
}
reactive和ref函数
在vue中,默认的数据不是响应式的,需要进行响应式就要用这两个函数来进行处理
reactive()
作用
接收一个对象类型的数据,返回一个响应式的对象。在vue3中,要实现响应式,一般就将需要的数据以对象的形式放到这个函数中
//创建一个不同JavaScript对象
const obj = {
name: 'username',
age: 18
}
//将对象放到函数中,返回的对象就可以实现响应式,试图和数据互相影响
import { reactive } from 'vue';
const reactiveObj = reactive(obj);
注意: reactive只接收对象数据类型
rel()
rel()用法和reactive()类似,但它既可以接收简单数据类型,也可以接收复杂数据类型,返回一个响应式对像
本质:
在 Vue 3 中,
ref函数用于创建一个包装器对象,将基本数据类型或对象转换为响应式数据。当你传入一个普通的 JavaScript 值(比如数字、字符串、布尔值等)给ref函数时,它会将这个值包装成一个具有响应式特性的对象。当你传入一个对象给
ref函数时,Vue 3 会对这个对象进行浅层包装,包装成一个具有value属性的对象。这个value属性指向原始对象,而ref返回的包装器对象则具有响应式特性。这种包装的过程是在
ref内部实现的,而不是依赖于reactive函数。虽然在某种程度上可以说ref借助了reactive函数来实现响应式,但它们之间并不是一种包含关系。
<script>
import { ref } from 'vue'
count = ref(0)
//拿值需要通过 .value 因为它外面又包了一层
console.log(count.value)
const setCount = () => {
count.value++
}
</script>
<template>
<div> {{ count }}</div>
<button @click="setCount">修改</button>
</template>
在我们的脚本 script中访问值需要.value,但在结构代码template中则不需要
computed
<script setup>
import { computed, ref } from 'vue'
// 声明数据
const list = ref([1,2,3,4,5,6,7,8,])
// 基于list 派生一个计算属性,从list中过滤 > 2
const computedList = computed(() => {
return list.value.filter(item => item> 2)
})
</script>
<template>
<div>
<div>原始数据: {{ list }}</div>
<div>计算后的数据: {{ computedList }}</div>
</div>
</template>
watch
<script setup>
import { ref, watch } from 'vue'
const count = ref(0)
const name = ref('张三')
const changeCount = () => {
count.value++
}
const changeName = () => {
name.value = '李四'
}
// 1.监听单个数据 watch(ref对象, (newValue, oldValue) => {})
watch(count, (newValue, oldValue) => {
console.log(newValue, oldValue)
})
// 2.监听多个数据 watch([ref对象1, 对象2], (newValue,oldValue) => {})
watch([count,name], (newValue, oldValue) =>{
console.log(newValue,oldValue)
})
// 3. ,watch是浅层监视,监视不到复杂数据类型内部数据的变化
const obj = ref({
uname: 'zy',
age: 18
})
const setInfo = () => {
// obj.value.age++
obj.value.uname = 'zt'
}
watch(obj, (newValue) => {
console.log(newValue)
}, {
deep: true //如果这里不开启深度监视,上面就打印不出变化后的新值
})
// 上面监听的是整个对象,如果我们只需要监听对象内部某一个属性的变化,写法又不一样
watch(() => obj.value.uname, (newValue,oldValue) => {
console.log(newValue,oldValue)
})
</script>
<template>
<div>{{ count }}</div>
<button @click="changeCount">改数字</button>
<div>{{ name }}</div>
<button @click="changeName">改名字</button>
<div>{{ obj }}</div>
<button @click="setInfo">复杂数据类型</button>
</template>