setup 参数
props 和 context
- props 用于获取组件中定义的 props
<template>
<div class="home">
<h2>{{ title }}</h2>
</div>
</template>
<script>
import {computed, ref, reactive, toRefs, watch} from 'vue';
export default {
name: 'Home',
components: {},
props: {
title: {
type: String,
default: 'hello world'
}
},
setup(props) {
console.log('props.title :>> ', props.title);
// 监听title发生改变
watch(
() => props.title,
(newTitle, oldTitle) => {
console.log('newTitle, oldTitle :>> ', newTitle, oldTitle);
}
);
}
};
</script>
-
context,在 setup 函数内不能使用 this,那么就可以使用 context 获取插槽
需要 title 发生改变时给发送一个事件, context.emit('change-title', title)
<template>
<div class="home">
<h2>{{ title }}</h2>
</div>
</template>
<script>
import {computed, ref, reactive, toRefs, watch} from 'vue';
export default {
name: 'Home',
components: {},
props: {
title: {
type: String,
default: 'hello world'
}
},
setup(props, context) {
console.log('props.title :>> ', props.title);
// 监听title发生改变
watch(
() => props.title,
(newTitle, oldTitle) => {
console.log('newTitle, oldTitle :>> ', newTitle, oldTitle);
context.emit('change-title', title);
}
);
}
};
</script>