2.组合式API知识点(1)
5 组合式API - reactive和ref函数
reactive()
例1:
在组合式api中,不需要用this拿到数据,直接就可以调用
<script setup>// 导入import { reactive } from 'vue'// 执行函数 传入参数 变量接收const state = reactive({msg:'this is msg'})const setSate = ()=>{// 修改数据更新视图state.msg = 'this is new msg'}
</script><template>{{ state.msg }}<button @click="setState">change msg</button>
</template>
ref()
6 组合式API - computed
computed计算属性函数
计算属性小案例
<script setup>
# 原始响应式数组
import { ref } from 'vue'
// 1. 导入computed
import { computed } from 'vue'
const list = ref([1, 2, 3, 4, 5, 6, 7, 8])// 2. 执行函数 return计算之后的值 变量接收
const promptedList = computed(() => {return list.value.filter(item => item > 2)
}setTimeout(() => {list.value.push(9, 10)
}, 3000)
</script><template>
<div>
原始响应式数组- {{ list }}
</div>
<div>
计算属性数组 - {{ computedList }}
</div>
</template>
07 组合式API - watch
watch函数
基础使用 - 侦听单个数据
<script setup>
import { ref, watch } from 'vue'
const count = ref(0)
const setCount = () => {count.value++;
}// TODO: watch侦听单个数据源
// ref对象不需要加.value
watch(count, (newVal, oldVal) => {console.log('count变化了', newVal, oldVal)
})</script><template>
<div><button @click="setCount">+{{ count }}</button></div>
</template>
基础使用 - 侦听多个数据
<script setup>
import { ref, watch } from 'vue'
const count = ref(0)
const setCount = () => {count.value++;
}const name = ref('cp')
const changName = () => {name.value = 'pc'
}// TODO: watch侦听多个数据源
// 侦听多个数据源
watch([count, name],([newCount, newName], [oldCount, oldName]) => {console.log('count或者name变化了', [newCount, newName],[oldCount, oldName])})</script><template><div><button @click="setCount">修改count--{{ count }}</button><button @click="changName">修改name--{{ name }}</button></div>
</template>
immediate
deep
精确侦听对象的某个属性
<script setup>
import { ref } from 'vue'
const state = ref({name: 'chaichai',age: 18
}const changeName = () => {// 修改namestate.value.name = 'chaichai-teacher'
}const changeAge = () => {// 修改age*state.value.age = 20
}// TODO:精确侦听某个具体属性
watch(()=>state.value.age,()=>{console.log('age变化了')
}
)<template>
<div><div>当前name -- {{ state.name }} </div><div>当前age -- {{ state.age }} </div><div><button @click="changeName">修改name</button><button @click="changeAge">修改age</button></div>
</div>
</template>
8 组合式API - 生命周期函数
Vue3的生命周期API (选项式 VS 组合式)
生命周期函数基本使用
执行多次
<scirpt setup>
import { onMounted } from 'vue'
onMounted(()=>{// 自定义逻辑
})onMounted(()=>{// 自定义逻辑
})
</script>