一.reactive()接收一个对象类型的数据,返回一个响应式的对象:
javascript
<script setup>
import {reactive} from 'vue'
const state = reactive({
count:100
})
const setCount =() => {
state.count++
}
</script>
<template>
<div>
<div>{{ state.count }}</div>
<button @click="setCount">+1</button>
</div>
</template>
二.ref()接收简单类型或者对象类型的数据传入并返回一个响应式对象
推荐声明数据,统一用ref
注意:脚本中访问数据,需要通过.value
在template中,.value不需要加(自动扒掉了一层)
javascript
<script setup>
import {ref} from 'vue'
const count = ref (0)
const setCount = () => {
count.value ++
}
</script>
<template>
<div>{{ count }}</div>
<button @click="setCount">+1</button>
</template>
三.computed计算属性
const 计算属性 = computed (() => {
return 计算返回的结果
}
javascript
<script setup>
import {computed,ref} from 'vue'
const list = ref([
1,2,3,4,5,6,7,8
])
const computedList = computed(() => {
return list.value.filter(item => item > 2)
})
</script>
<template>
<div>
<div>原始数据:{{ list }}</div>
<div>计算后数据:{{ computedList }}</div>
</div>
</template>
增加一个修改函数
javascript
<script setup>
import {computed,ref} from 'vue'
const list = ref([
1,2,3,4,5,6,7,8
])
const computedList = computed(() => {
return list.value.filter(item => item > 2)
})
const addFn = () =>{
list.value.push(666)
}
</script>
<template>
<div>
<div>原始数据:{{ list }}</div>
<div>计算后数据:{{ computedList }}</div>
</div>
<button @click="addFn">修改添加</button>
</template>
注意:计算属性不应该有"副作用",比如异步请求/修改dom
避免直接修改计算属性的值,计算属性应该是只读的,特殊情况可以配置get set
四.watch函数
作用:侦听一个或者多个数据的变化,数据变化时执行回调函数
俩个额外参数:1.immediate(立即执行) 2.deep(深度侦听)
1,侦听单个数据
- 导入watch函数
- 执行watch函数传入要侦听的响应式数据(ref对象)和回调函数
watch(ref对象,(newValue,oldValue) => {...} )
javascript
<script setup>
import {ref,watch} from 'vue'
const count = ref(0)
const nickname = ref('张三')
const changeCount = () =>{
count.value++
}
const changeNickname = () =>{
nickname.value = '李四'
}
//1.监视单个数据变化
// watch(ref对象,(newValue,oldValue) => {...})
watch(count,(newValue,oldValue) => {
console.log(newValue,oldValue)
})
<template>
<div>{{ count }}</div>
<button @lick="changeCount">改数字</button>
<div>{{ nickname }}</div>
<button @click="changeNickname">改昵称</button>
</template>
2,侦听多个数据
watch( [ref对象1,ref对象2],(newArr,oldArr) => {...} )
javascript
<script setup>
import {ref,watch} from 'vue'
const count = ref(0)
const nickname = ref('张三')
const changeCount = () =>{
count.value++
}
const changeNickname = () =>{
nickname.value = '李四'
}
</script>
<template>
<div>{{ count }}</div>
<button @lick="changeCount">改数字</button>
<div>{{ nickname }}</div>
<button @click="changeNickname">改昵称</button>
</template>