setup()两个参数:
1.props:值为对象,包含:组件外部传递过来。切组件内部声明接收了的属性
2.context :上下文对象
- attrs:值为对象,包含组件外部传递过来,但没有在props配置中声明的属性。相当于this.$attrs
- slots:收到的插槽内容,相当于this.$slots
- emit:分发自定义事件的函数,相当于this.$emit
props代码示例:
父组件代码:
<template>
<div id="nav">
<About :name="obj.name1" :age="obj.age1" ></About>
</div>
</template>
<script>
import About from './views/About'
import Home from './views/Home'
export default {
name: 'App',
setup(){
let obj = {
name1:'孙悟空',
age1:11,
name2:'沙和尚',
age2:99,
}
return {
obj
}
},
components:{
About,
Home
}
}
</script>
<style lang="scss">
</style>
子组件代码:
<template>
<div class="hello">
<div>
<h1>姓名:{{obj.name}}</h1>
<h1>年龄:{{obj.age}}</h1>
<h1>爱好:{{obj.hobby}}</h1>
</div>
</div>
</template>
<script>
import {reactive} from 'vue'
export default {
name: 'About',
props:['name','age'],
setup(props) {
console.log('---setup--- ',props)
let obj = reactive({
name:props.name,
age:props.age,
hobby:['游泳','音乐']
});
return {
obj,
}
},
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
效果图:
context代码示例:
子组件代码:
<template>
<div class="hello">
<div>
<h1>姓名:{{obj.name}}</h1>
<h1>年龄:{{obj.age}}</h1>
<h1>爱好:{{obj.hobby}}</h1>
<button @click="test">点击传值</button>
</div>
</div>
</template>
<script>
import {reactive} from 'vue'
export default {
name: 'About',
props:['name','age'],
setup(props,context) {
// console.log('---setup--- ',props);
console.log('---setup--- ',context);
console.log('---setup--- ',context.emit);
let obj = reactive({
name:props.name,
age:props.age,
hobby:['游泳','音乐']
});
function test() {//通过context下面的emit进行事件传递
context.emit('hello','子组件参数:哈哈哈')
}
return {
obj,
test
}
},
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
父组件代码:
<template>
<div id="nav">
<About :name="obj.name1" :age="obj.age1" @hello="helloMsg"></About>
</div>
</template>
<script>
import About from './views/About'
import Home from './views/Home'
export default {
name: 'App',
setup(){
let obj = {
name1:'孙悟空',
age1:11,
name2:'沙和尚',
age2:99,
};
function helloMsg(val) {//val就是子组件传递过来的参数
alert(`触发了hello事件,我收到的参数是:${val}`)
}
return {
obj,
helloMsg
}
},
components:{
About,
Home
}
}
</script>
<style lang="scss">
</style>
效果图:
以上就是setup参数的基本使用。