vue3中新的用法<script setup></script>
将setup
放在<script></script>
中
emit 子组件向父组件传值
子组件 child.vue
<script setup>
const state = reactive({
active: '1234'
})
const emit = defineEmits(['confirm'])
const confirm = () => {
emit('confirm', state.active)
}
<script>
父组件 parent.vue
<child @confirm="confirm"/>
import child from './child.vue'
const confirm = (value) => {
console.log(value, '子组件传过来的值')
console.log('这里是父组件')
}
props 父组件向子组件传值
父组件 parent.vue
<child :parentValue="parentValue" :parentFunction="parentFunction"/>
import child from './child.vue'
import { reactive, toRefs } from 'vue' // 引入
const state = reactive({
parentValue: '我是parent中的值'
})
const { parentValue } = toRefs(state)
const parentFunction = () => {
console.log('我是parent中的方法')
}
子组件 child.vue
<template>
{{parentValue}}
</template>
<script setup>
const props = defineProps({
parentFunction: Function,
parentValue: {
type: String,
default: ''
}
})
console.log(props.parentValue, props.parentFunction) // 在 script 中使用的时候 需要带上 props
</script>
使用子组件中的变量合方法 — ref 和defineExpose
子组件 child.vue
<script setup>
import { reactive, toRefs } from 'vue'
const childFunction = () => {
console.log('子组件中的方法')
}
const state = reactive({
childState: 'child'
})
defineExpose({ // 一定要使用 defineExpose 将你要在父组件中使用的方法 导出
childFunction,
state.childState
})
</script>
父组件 parent.vue
<child ref="child"/>
import child from './child.vue'
import { reactive, toRefs, ref } from 'vue' // 引入
const child = ref(null)
console.log(child.value.childFunction, child.value.childState)
}