数据定义和取值
基本数据
let count = ref(0) //类型为Object
// 取值:
const countChange = ()=> {
count.value += 1
console.log('========', count.value)
}
Object 响应式数据
let dataJson = reactive({'key': 'ios'}) //定义Object
console.log('========', dataJson) // reactive 数据取值
生命周期使用
生命周期写法就这样格式
onMounted(()=>{
console.log('======', count)
})
onBeforeMount(()=>{
})
观察者 watch
// 观察单一数据
watch(count, (newVal, oldVal)=>{
console.log('change=======>>>>', count.value)
}, {immediate: true, deep: true})
// 整个页面中数据变化调用
watchEffect(()=>{
console.log('change=====', count.value)
})
computed 计算属性(使用频率高)
// computed 计算属性
const computData = computed(()=> count.value + 'hello')
onMounted(()=>{
console.log('====', computData.value)
})
watch(computData, ()=>{
console.log('====computed', computData.value)
})
推送和订阅
父组件向子组件推送消息,无论子组件是多少层级
// 消息推送
provide('numberChange', count)
// 订阅
let injectCount = inject('numberChange')
父子组件传值
// 组合式API写法,其他部分和Vue2一致
import { onMounted, defineEmits} from 'vue';
const emits = defineEmits(['sendData'])
emits(actions.sendData, 'hello world!!!')
nextTick 语法糖
import {nextTick } from 'vue';
nextTick(()=>{
console.log('sendData====', value)
})
ref方式调用子组件的方法和属性
子组件写法
// 暴露方法
const exposeFunction = ()=>{
console.log('expose function')
}
enum actions {
sendData = 'sendData'
}
defineExpose({
// 方法
exposeFunction,
// 枚举
actions
})
父组件
// 子组件 ref标识为demo
<detail-control ref="demo" @sendData='sendData'></detail-control>
// 定义子组件,ref()函数可不传值,根据demo的标识匹配
const demo = ref()
注意父子组件加载的生命周期规律可知道,父组件获取子组件的dom节点,需在父组件加载完成之后,所以需要在onMounted周期之后
onMounted(()=>{
// 调用demo的节点的方法或者属性
demo.value.exposeFunction()
console.log('demo===', demo.value)
})