Vue3.0的学习还在继续。开始下一步的学习。这一次主要针对 watch 和 computed
watch
import { watch, ref, reactive } from 'vue'
export default {
setup() {
const name = ref('ms')
const otherName = reactive({
firstName: '马',
lastName: '赛'
})
watch(name, (newValue, oldValue) => {
// 输出 马赛 ms
console.log(newValue, oldValue)
})
// watch 可以监听一个函数的返回值
watch(
() => {
return otherName.firstName + otherName.lastName
},
value => {
// 当otherName中的 firstName或者lastName发生变化时,都会进入这个函数
console.log(`我叫${value}`)
}
)
setTimeout(() => {
name.value = '马赛'
otherName.firstName = '王'
}, 3000)
}
}
watch除了可以监听单个值或者函数返回值之外,也可以同时监听多个数据源
export default {
setup() {
const name = ref('马赛')
const gzh = ref('vue')
watch([name, gzh], ([name, gzh], [prevName, prevGzh]) => {
console.log(prevName, name)
console.log(prevGzh, gzh)
})
setTimeout(() => {
name.value = 'ms'
gzh.value = 'react'
}, 3000)
}
}
在学习中在大佬文章中查阅到还有一个 watchEffect
watchEffect
watchEffect的用法与watch有所不同,watchEffect会传入一个函数,然后立即执行这个函数,对于函数里面的响应式依赖会进行监听,然后当依赖发生变化时,会重新调用传入的函数
import { ref, watchEffect } from 'vue'
export default {
setup() {
const id = ref('0')
watchEffect(() => {
// 先输出 0 然后两秒后输出 1 id value的变化产生变化。
console.log(id.value)
})
setTimeout(() => {
id.value = '1'
}, 2000)
}
}
computed
计算属性
export default {
setup() {
const info = reactive({
firstName: '马',
lastName: '赛'
})
const name = computed({
get: () => info.firstName + '-' + info.lastName,
set(val) {
const names = val.split('-')
info.firstName = names[0]
info.lastName = names[1]
}
})
return {
name
}
}
}
Vue3.0 也算友好,可以使用组合式API 但也可以兼容2.0 的内容 即 data methods 接下来我们要学习下 Vuex 以及 新版 Vue 存储库 Pinia