去官网学习→组合式 API:setup() | Vue.js
运行示例:
代码:App.vue
<template><div class="home"><img alt="Vue logo" src="../assets/logo.png"><!-- msg 组件传递数据 --><HelloWorld msg="vue setup()新特性 "/></div>
</template><script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'export default {name: 'HomeView',components: {HelloWorld}
}
</script>
代码:HelloWorld.vue
<template><h2>Vue3 setup新特性</h2><p>{{msgs}}</p><p>{{cont}}</p><p v-for="(item,index) in names.list" :key="index">{{ item }}</p><button @click="clickBtn">点击事件</button><p>{{msg}}</p><p>父组件传递过来的数据-》{{ superData }}</p>
</template><script>
//需要什么就引用啥
import { ref,reactive, onMounted, onBeforeMount, onBeforeUpdate,onUpdated, onBeforeUnmount, onUnmounted,inject } from 'vue'; export default {name: 'HelloWorld',props:{msg:String,default:"默认值"},data(){return{msgs :"消息"}},//组合式API setup 中没有thissetup(props,context){//Proxyconsole.log(props);// Setup 上下文对象console.log(context);//refconst cont = ref("这是内容");//reactiveconst names = reactive({list:["admin","user","tom"]});//方法function clickBtn(){//alert("点击事件");//.valuecont.value = "修改后的数据----"}//props 组件传递数据const msg = props.msg//setup 生命周期 可以调用多次onMounted(() =>{console.log("------onMounted渲染完成------");});onBeforeMount(() =>{console.log("------onMounted渲染之前------");});//beforeUpdateonBeforeUpdate(() =>{console.log("------onBeforeUpdate更新之前------");});onUpdated(() =>{console.log("------onUpdated更新完成------");});onBeforeUnmount(() =>{console.log("------onBeforeUnmount卸载之前------");});onUnmounted(() =>{console.log("------onUnmounted卸载完成------");});// inject("key") 子组件接收父组件数据const superData = inject("superMsg");//returnreturn{cont,names,clickBtn,msg,superData}}}
</script>