Table of contents
2. Properties and events defineProps, defineEmits
1. Basic use
- Top-level variables, custom components, can be used directly in templates (do not need export setup function return)
- Capabilities such as ref reactive computed can be used normally
- Used with other <script>
- <script setup> is written before <template>
Code demo:
<script setup>
import { ref, reactive, toRefs } from 'vue'
import SetupChild from './SetupChild.vue'
const countRef = ref(100)
const state = reactive({
name: 'zhangsan',
age: 23
})
const { age } = toRefs(state)
function addCount () {
countRef.value++
}
console.log(add(10, 20))
</script>
<script>
function add (a, b) {
return a + b
}
</script>
<template>
<p @click="addCount">{
{ countRef }}--{
{state.name}}--{
{age}}</p>
<SetupChild />
</template>
2. Properties and events defineProps, defineEmits
- defineProps (array or object can be passed)
- defineEmits (triggered in js, triggered in template)
Code demo:
// 父组件
<script setup>
import { ref, reactive, toRefs } from 'vue'
import SetupChild2 from './SetupChild2.vue'
const countRef = ref(100)
const state = reactive({
name: 'zhangsan',
age: 23
})
const { age, name } = toRefs(state)
function onChange (info) {
console.log('on change', info)
}
function onDelete (info) {
console.log('on delete', info)
}
</script>
<template>
<SetupChild2 :name="name" :age="countRef" @change="onChange" @delete="onDelete"/>
</template>
// 子组件
<script setup>
import { defineProps, defineEmits } from 'vue'
// 定义属性 defineProps
// defineProps(['name', 'age'])
const props = defineProps({
name: String,
age: Number
})
// 定义事件 defineEmits
const emit = defineEmits(['change', 'delete'])
function deleteHandler () {
emit('delete', 'bbbb')
}
</script>
<template>
<p>child2</p>
<p>name: {
{ props.name }} -- age: {
{ props.age }}</p>
<button @click="$emit('change', 'aaa')">change</button>
<button @click="deleteHandler">delete</button>
</template>
3. defineExpose
- Child components expose data to parent components through defineExpose
- The parent component gets data through ref
Code demo:
// 父组件
<script setup>
import { ref, reactive, toRefs, onMounted } from 'vue'
import SetupChild3 from './SetupChild3.vue'
const child3Ref = ref(null)
onMounted(() => {
// 拿到 child3 组件的一些数据
console.log(child3Ref.value) // proxy
console.log(child3Ref.value.a) // 100
console.log(child3Ref.value.b) // 200
})
</script>
<template>
<SetupChild3 ref="child3Ref"/>
</template>
// 子组件
<script setup>
import { ref, defineExpose } from 'vue'
const a = ref(100)
const b = 200
defineExpose({
a,
b
})
</script>
<template>
<p>Child 3</p>
<p>{
{ a }} {
{ b }}</p>
</template>