Vue3可以通过ref来创建基础响应式的变量
<template>
{{a}}
{{b}}
{{c}}
{{c[0]}}
</template>
import { ref } from 'vue'
setup(){
const a = ref(0)
const b = ref('xiaowang')
const c = ref(['hh','kk'])
return {
a,b,c
}
}
尝试更改数组c中的元素值,测试数组基本操作方法以及直接赋值,看看响应式变化
const changeValue = () => { c.unshift('66') }
return { changeValue } // 这里就会有问题了,因为c是ref的array类型所以是没有unshift方法的,如果想拿到ref引用的值要加.value
也就是写成:
c.value.unshift('66')
其他的也要加.value才行: a.value b.value
可以总结一下一般简单数据类型习惯用ref,而且也是响应式的,无论是赋值还是使用方法改变值都是可以的
const a = ref(0)
const b = ref(true)
const c = ref('')
const d = ref([])
const e = ref({}) // 对象目前还是采取reactive里面定义普通类型再转成ref比较好用
toRefs方法能够让结构/扩展...,返回的对象不丢失响应性
function useFeatureX(){
const state = reactive({
foo: 1,
bar: 2
})
}
return { ...toRefs(state) }
export default {
setup() {
const { foo, bar } = useFeatureX
return { foo, bar}
}
}
定义方法的时候直接const箭头函数就可以了,最好还是用ts,定义好入参类型和函数返回类型,随便的就用any就行
const setValue = (str: string):void => {
state.value = str
}
这里开始研究一下ts的类型锁定,目前暂时发现有这些写法
interface Book { // 这里定义了一下可能用到的类型的接口
title: string,
author: string,
year?: number, // 可有可无
}
props: { // props里面的是大写的,额。。。
f: Number,
a: Boolean,
n: String,
success: { type: String },
getValue: { type: Function as PropType<() => {}> },
jj: { type: Function as PropType<() => void> },
book: {
type: Object as PropType<Book>,
required: false
}
},
我们也可以在定义ref的时候和定义reactive的时候固定类型
const a = ref<number>(1)
const b = ref<string>('aaa')
const book = reactive<Book>({
title: '1',
author: '2'
// d: '3'
})
接下来是生命周期函数,常用的也就是onMounted了,在setup中是一个function的调用
setup由于比vue2的created执行还要早,所以说onMounted方法也会比mounted方法更早执行,但是还是兼容之前的写法的,
onMounted(()=>{
const { currentRoute: { _value: { query }} } = router
state.name = query.name
})
// 这里解析router传过来的值我也没发现什么好方法,也就在这里很复杂的解析了一下
路由跳转也就直接router.push()就好了
router是在vue-router中调用useRouter拿到的
import { useRouter } from 'vue-router'
const router = useRouter()
对于计算属性也有了新的变化,直接也是函数式编程的方式,调用computed方法,里面传入一个function拿到返回值
const count = computed(() => store.state.count)
//watch方法如果监听ref和监听reactive中的数据写法是不一样的
//监听ref
const count = ref(1)
watch(count,(newVal, oldVal) => { })
//监听reactive
const state = reactive({
count: 1
})
watch(()=>state.count,(newVal, oldVal) => {})
新增了watchEffect方法
如果函数中引用值发生了修改,会执行回调
watchEffect(()=>{console.log(count.value)})
关于vuex
import { InjectionKey } from 'vue'
import { createStore, Store } from 'vuex'
export interface State {
count: number
}
export const key: InjectionKey<Store<State>> = Symbol()
export const store = createStore<State>({
state() {
return {
count: 0
}
},
mutations: {
increment(state) {
state.count++
}
}
})
调用的时候先拿到key,然后再用vuex中的userStore,这样就知道调用哪个
import { useStore } from 'vuex'
import { key } from '../store'
const store = useStore(key)
const count = computed(() => store.state.count)
store.commit('increment') // 触发mutations中的方法