上次写到基本的脚手架,详情点击: 从0开始创建vue3.0+vite+ts(一)
今天来讲讲基础使用
- 父子组件间传参
父子组件间传参
父传子 之 props
父组件 index.vue
<template>
<div>
<!-- 子组件 -->
<Child msg="这是父组件数据" />
</div>
</template>
<script setup lang="ts">
import Child from '@/components/Child.vue'
</script>
子组件 Child.vue
<template>
<!-- 这是子组件 -->
<div> {{msg}} </div>
</template>
<script setup type='ts'>
const props = defineProps({
msg: { type: String, default: '这是默认数据' }
})
</script>
子传父 之 emit
父组件 index.vue
<template>
<div>
<!-- 子组件 -->
<Child @change="onChange" />
{{ msg }}
</div>
</template>
<script setup lang="ts">
import Child from '@/components/Child.vue'
import { ref } from 'vue'
const msg = ref<string>('这是默认数据')
function onChange(v: string) {
msg.value = v
}
</script>
子组件 Child.vue
<template>
<!-- 这是子组件 -->
<div>
<el-button @click="onClick">传值给父组件</el-button>
</div>
</template>
<script setup type='ts'>
const emit = defineEmits(['change'])
function onClick(){
emit('change', '这是子传给父的数据')
}
</script>
子传父 之 副作用(不推荐使用)
父组件 index.vue
<template>
<div>
<!-- 子组件 -->
<Child :obj="obj" />
obj== {{ obj }}
</div>
</template>
<script setup lang="ts">
import Child from '@/components/Child.vue'
import { ref } from 'vue'
const obj = ref<object>({
title: '这是默认title'
})
</script>
子组件 Child.vue
<!-- 这是子组件 -->
<div>
<el-button @click="onClick">传值给父组件</el-button>
</div>
</template>
<script setup type='ts'>
const props = defineProps({
obj: Object
})
function onClick(){
props.obj.title = '这是子传给父的title'
}
</script>
父子组件间方法调用
子组件调用父级方法参考上面提到的 emit
这里说说父级调用子组件的方法函数
这里使用 ref 实现调用,使用 defineExpose 暴露属性以及方法
父组件 index.vue
<template>
<div>
<!-- 子组件 -->
<Child ref="ChildRef" />
<el-button @click="onClick">触发子组件方法</el-button>
</div>
</template>
<script setup lang="ts">
import Child from '@/components/Child.vue'
import { ref } from 'vue'
const ChildRef = ref<null | HTMLElement>(null)
function onClick() {
ChildRef?.value?.open('1111')
}
</script>
子组件 Child.vue
<template>
<!-- 这是子组件 -->
<div>
{{ msg }}
</div>
</template>
<script setup type='ts'>
import { defineExpose, ref } from 'vue'
const msg = ref('这是默认数据')
const open = function (v) {
msg.value = v
}
defineExpose({ // 暴露出去的属性以及方法
open
})
</script>