setup() 接受二个参数 :props、context(有三个值)
props:父组件传进来,并且声明(声明示例下方代码有标注)过的值
context:1.attrs 外部传进来 但是没有声明过的值;
2.slots 通过插槽传进来的内容(下方代码没有验证,感兴趣的可以自己试一试);
3.emit 分发自定义事件。
首先写一个子组件的demo
<template>
<h1 @click="hello2">{{ info.age }}</h1>
<h1 @click="hello">{{ info.obj.sex }}</h1>
<h1 @click="addGirl">女孩:{{ info.likeGirl }}</h1>
<h1 @click="hello2">{{ age }}</h1>
<button @click="text">点击触发父组件的自定义事件‘hello’</button>
</template>
<script>
import { reactive } from "vue";
export default {
name: "Demo",
//声明外部传入的值
props:['msg','school'],
声明外部的事件
emits:['hello'],
setup(props,context) {
console.log(props)
/* let name = ref("小蜜瓜");
let age = ref(12);
let obj = reactive({
name:'南瓜',
sex:'女'
})
let likeGirl = reactive(['倪妮','刘浩存'])
function hello2() {
age.value = 13
console.log(obj)
obj.sex = '不详'
likeGirl[0]='孙'
} */
function text(){
context.emit('hello','我收到了')
}
function addGirl() {
info.likeGirl.push("倪妮");
}
let hello = () => {
alert(`我是${info.name}`);
};
let info = reactive({
name: "小蜜瓜",
likeGirl: ["宋佳", "刘浩存"],
age: 12,
obj: {
name: "南瓜",
sex: "女",
},
});
return {
info,
addGirl,
hello,
text
};
},
};
</script>
<style>
</style>
将子组件引入父组件
<template>
<Demo msg="我得" school="二中" @hello="dialogOne"/>
</template>
<script>
// import { reactive } from "vue";
import Demo from './commponents/test.vue'
export default {
components: { Demo },
name: "App",
setup(){
function dialogOne(val){
alert (`我是小艾,${val}`)
};
return{
dialogOne
}
}
};
</script>
<style>
</style>