在 Vue3.0 中使用 conText
setup 中可以有两个参数 第一个参数就是 props 第二个参数就是 context
context 解释
context.parent === this.$parent
context.root === this
context.emit === this.$emit
context.refs === this.$refs
context.slots === this.slots
在 context 里面可以选择 attrs,slots,emit
export default {
setup(props, context) {
// Attributes (Non-reactive object)
console.log(context.attrs)
// Slots (Non-reactive object)
console.log(context.slots)
// Emit Events (Method)
console.log(context.emit)
},
}
在 context 使用 emit
子组件 利用 emit 发射出去
<template>
<div>
<div>{{name}}</div>
<div>{{message}}</div>
</div>
</template>
<script>
import { toRefs } from 'vue'
export default {
props: { name: String },
setup(props, context) {
const { name } = toRefs(props)
let message = name.value + '今天天气不错'
//把数据发送走
context.emit('fashe', message)
return {
message,
}
},
}
</script>
<style lang="less" scoped></style>
父组件监听
- 必须要把监听的函数暴露出去
<template>
<div>
<span>{{count}}</span>
<span>{{double}}</span>
<div @click="changecount">点击增加</div>
<H1Component :name="data2" @fashe="shoudao"></H1Component>
<div>{{data3}}</div>
</div>
</template>
<script>
import { ref, computed, reactive, toRefs, onMounted, watch } from 'vue' //ref接收一个参数 返回一个响应式对象 //computed是一个函数接收一个参数是函数
import H1Component from './H1.vue'
export default {
components: {
H1Component,
},
setup() {
onMounted(() => {
console.log('挂在了')
})
const data = reactive({
count: 0,
double: computed(() => {
return data.count * 2
}),
changecount: () => {
data.count++
},
})
let data2 = ref('哈哈,')
let data3 = ref('接收到数据是:')
watch(data2, (newval, oldval) => {
console.log(data2)
console.log(newval)
console.log(oldval)
})
function shoudao(content) {
data3.value = data3.value + content
console.log(data3)
}
const result = toRefs(data)
return {
...result,
data2,
data3,
shoudao,
}
},
}
</script>
<style lang="less" scoped></style>