setup
選項是一個接收props
和context
的函數。此外,setup
返回的所有內容都暴露給組件的其余部分 (計算屬性、方法、生命周期鈎子等等) 以及組件的模板。
<script lang="ts">
export default { // vue3.0寫法
name: 'Home',
setup (props, context) {
console.log(props, context);
const name = '1111'
return {
name
}
}
}
</script>
<script setup lang="ts"> // vue3.2寫法,最新寫法
import { ref, reactive } from 'vue'
const name = ref('1') // 響應式數據
const name1 = ref([]) // 這也是響應式數據,官方的意思是數組和對象有變化后能自動響應,但是我實際使用ref也是一樣可以響應
</script>
子組件接收參數
const props = defineProps({
// 寫法一
msg2: String
// 寫法二
msg2:{
type:String,
default:""
}
})
子組件傳遞參數回父組件
// defineEmits 這個不需要引入,3.0版本沒試過,用的是3.2版本
const emit = defineEmits(["myClick","myClick2"])
// 對應寫法二
const handleClick = ()=>{
emit("myClick", "這是發送給父組件的信息")
}
此文章借鑒了這位大佬的文章