vue3 新增的核心东西
Composition API
使用了 Proxy 实现响应式
全新的全家桶
全新的 TS 支持
vite
Composition API:组合式 API
Vue3 响应式变量声明
推荐 使用 ref 声明 基础数据类型 的变量
import { ref } from 'vue'
const count = ref(0)
const addCount = () => {
count.value++
}
- 注意:
- 想要使用 ref, 必须先 import 导入它
- Ref 声明出来的响应式数据, 想要访问必须通过 .value
推荐使用 reactive 声明 引用数据类型 的变量
import { ref } from 'vue'
const obj = reactive({
name: 'feifei',
age: 18,
sex: '男'
})
const addAge = () => {
obj.age++
}
computed
import { ref, computed } from 'vue'
const count = ref(0)
const doubleCount = computed({
get() {
return count.value * 2
},
set(val) {
count.value = val / 2
}
})
watch
import { watch, reactive } from 'vue'
const state = reactive({
count: 1
})
const changeCount = () => {
state.count = state.count * 2
}
watch(
() => state.count,
(newVal, oldVal) => {
console.log(state.count)
console.log(`watch监听变化前的数据:${oldVal}`)
console.log(`watch监听变化后的数据:${newVal}`)
},
{
immediate: true,
deep: true
}
)
const count = ref(0)
watch(count, (count, prevCount) => {
})
注意
生命周期钩子
小结
- created 用 setup 代替
- mounted <=> onMounted
过滤器移除
我们建议用计算属性或方法代替过滤器,而不是使用过滤器。
全局属性 代替 全局过滤器
const app = createApp(App)
app.config.globalProperties.$filters = {
currencyUSD(value) {
return '$' + value
}
}
<template>
<h1>Bank Account Balance</h1>
<p>{{ $filters.currencyUSD(accountBalance) }}</p>
</template>
注意,这种方式只适用于方法,而不适用于计算属性,因为后者只有在单个组件的上下文中定义时才有意义。