vue3简明教程实践

// ParentComponent
<script setup lang="ts">
// reactive 创建响应式对象数据
import {ref, reactive, toRefs, computed, watch, onMounted, provide } from 'vue';
// 一般创建简单类型的数据,例如字符串、布尔值等
const number = ref(0);
const changeNumber = () => {
  // 修改数据必须加上.value
  number.value++
}
// 一般用来创建对象、数组类型数据
const userInfo = reactive({
  name: 'leyi',
  role: 'front-developer',
  introduce: 'nobody'
})
const changeUserInfo = () => {
  userInfo.introduce = 'my name is leyi, i was born in sichuan'
}

// 解构reactive创建的响应式对象
const { name, role, introduce } = toRefs(reactive({
  name: 'leyi',
  role: 'front-developer',
  introduce: ''
}))
const changeUserInfoDeconstruction = () => {
  introduce.value = 'a province well know for its spicy food'
  console.log(userInfo.introduce) // 检查是否执行
}
// 计算属性
const tripledNumber = computed(() => number.value + 3)

// 数据监听 类似effect
watch(number, (newValue, olValue) => {
  console.info('number changed', newValue, olValue)
})

// 父组件穿传递数据给子组件
import ChildComponent from './myComponents/ChildComponent.vue'

// 获取子组件传递过来的数据
const getChildData = (data) => {
console.info('data from child', data)
}

// 通过ref获取组件实例Dom
const btnRef = ref(null)
onMounted(() => {
  console.info('btnRef', btnRef.value)
})

// 调用子组件里的方法 子组件通过defineExpose进行暴露
const childComponentRef = ref(null)
const changeChildComponentContent = () => {
  childComponentRef.value.changeContent()
}

// 通过provide往下传递数据,所有子孙组件都能接收到 类似于contextProvider
provide("list", [5,6,7,8,9])
</script>

<template>
<div>
  {{ number }}
  <button @click="changeNumber">modify number</button>
</div>
<div>
  {{ userInfo.name }}
  {{ userInfo.role }}
  {{ userInfo.introduce}}
  <button @click="changeUserInfo">modify userInfo</button>
</div>
<div>
  {{ name }}
  {{ role }}
  {{ introduce }}
  <button @click="changeUserInfoDeconstruction">modify userInfo deconstruction</button>
</div>
<div>
  {{ tripledNumber }}
</div>
<div>
  <ChildComponent :data="userInfo" @getChildData="getChildData"  ref="childComponentRef"/>
</div>
<div>
  <button ref="btnRef">get current ref instance dom </button>
</div>
<div>
  <button @click="changeChildComponentContent"> invoke function or attribute of  child component</button>
</div>
</template>
// ChildComponent
<script setup>
import { ref, inject } from 'vue'
// 通过props从父组件获取数据
const props = defineProps(['data'])
console.info('props', props.data.name)
// 通过emit注册事件向父组件传递数据
const emit = defineEmits(['getChildData'])
const sendMessage = () => {
  emit('getChildData', [1,2,3,4,5])
}

// 通过defineExpose向父组件暴露方法或属性
const content = ref('hello world')
const changeContent = () => {
  content.value = 'hello leyi'
}
defineExpose({
  content,
  changeContent,
})

// 通过inject接收数据
console.info('received data from above components', inject('list'))
</script>
<template>
<button @click="sendMessage">send data to parent component</button>
{{ content }}
</template>

 

参考文档:https://mp.weixin.qq.com/s/_f9g9kiaG1HmG-KXHjgCRw

posted @ 2025-07-25 13:51  韭菜茄子  阅读(8)  评论(0)    收藏  举报