目录
2. 属性和事件 defineProps,defineEmits
1. 基本使用
- 顶级变量,自定义组件,可以直接用于模板(不需要 export setup 函数 return)
- 可正常使用 ref reactive computed 等能力
- 和其他 <script> 同时使用
- <script setup> 写在 <template> 前面
代码演示:
<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. 属性和事件 defineProps,defineEmits
- defineProps(可传数组或对象)
- defineEmits(js中触发,模板中触发)
代码演示:
// 父组件
<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
- 子组件通过 defineExpose 暴露数据给父组件
- 父组件通过 ref 获取数据
代码演示:
// 父组件
<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>