1 常规写法
<script lang="ts">
import { onMounted, reactive, ref, toRef, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
export default {
setup() {
const $router = useRouter();
const $route = useRoute(); //使用路由
let name = ref("星星");//响应式的变量
let num =11;//不具备响应式的变量
onMounted(() => { //生命周期钩子函数
console.log($route.path);
});
const handleChange = () => { //定义方法
console.log(name.value);
};
return {
name,num,handleChange //将变量和方法return出去给页面使用
};
},
};
</script>
2 语法糖写法,没有了export,这种形式的ref实例默认都会自动return出去,直接使用即可
<script lang='ts' setup>
import { reactive, ref } from "vue";
let name = ref("李星辰");
let data = reactive({uname: "lxc",age: 18,});
</script>
<div>{{name}}</div> <div>{{data.uname}}</div>
3 父子传参setup()写法
setup中没有this实例,不能使用this,因此提供了context对象用来调用3个最常用方法attrs、slot 和emit
父子传值方式:setup()可以接收2个参数props和context,context可以调用emit等方法
父组件
<template>
<TestSon :msg='msg'></TestSon>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import TestSon from './testson.vue'
export default defineComponent({
components:{
TestSon
},
setup(props,context) {
let msg ='hello'
const showAlert = (param: any) => {
alert(param)
};
return {
msg,
showAlert
};
},
});
</script>
子组件
<template>
<button @click="handleClick">触发父组件方法</button>
</template>
<script lang="ts">
export default {
props:{
msg:{
type:String,
required:true
}
},
emits:[
'showAlert'
],
setup(props,context) {
const handleClick = ()=>{
context.emit('showAlert',props.msg) //触发方法并传参
}
return {
msg:props.msg,
handleClick
}
},
};
</script>
4 父子传参语法糖写法,引入组件可能报错误提示-子组件没有导出,但这个是插件的问题,实际可以运行
父组件
<template>
<TestSon :msg="msg" @showAlert="showAlert"></TestSon>
</template>
<script lang="ts" setup>
import { ref } from "vue";
let msg = ref("hello");
const showAlert = (param: any) => {
alert(param);
};
</script>
子组件
<template>
<button @click="handleClick">触发父组件方法</button>
</template>
<script lang="ts" setup>
import { defineEmits,defineProps,toRefs } from "vue";
const props =defineProps({
msg:String
})
const emit=defineEmits(['showAlert'])
const {msg}=toRefs(props)
const handleClick = ()=>{
emit('showAlert',msg?.value)
}
</script>
<1> 子组件指定接收类型
const props =defineProps({
msg:String,
arr:Array
})
在ts语法里还可以写成
const props = defineProps<{
msg:string,
arr:string[]//字符串的数组
}>()
<2> 子组件赋默认值
type Props = { //这个地方网上有另一种写法 interface Props {msg?: string,arr?: string[]}
msg: string,
arr: string[]
}
const props = withDefaults(defineProps<Props>(), { //为了能够使用props的值,加上const props=,原博文上没有
msg: () => '孙悟空',
arr: () => ['1', '2', '3']
})
<3> 通过ref直接调用子组件实例
子组件中
defineExpose({
data,//向父组件暴露的参数
childFunc //向父组件暴露的方法
})
父组件中
<template>
<TestSon ref="child" :msg="msg" @showAlert="showAlert"></TestSon>
</template>
child.value.data 可以获取子组件值
child.value.childFunc() 可以调用子组件方法