参考文档
参考文档:https://blog.csdn.net/ll666888999/article/details/123789098
参考视频:https://www.imooc.com/learn/1300
官方文档查看文档:https://v3.cn.vuejs.org/
准备工作
- 在views底下新建一个父组件Home.vue
- 在components中创建三个文件夹,三个子组件navheader,navmain,navfooter
Home.vue里面开始写代码 代码主要内容如下
- 把子组件引入到父组件当中
import NavHeader from ‘@/components/navHeader/NavHeader.vue’ import NavMain from ‘@/components/navMain/NavMain.vue’ import NavFooter from ‘@/components/navFooter/NavFooter.vue’
- 把import从vue中解构出来
import {defineComponent} from ‘vue’
- 定义组件
export default defineComponent({ name: "Home", props: {}, components: { NavHeader, NavMain, NavFooter, }, setup(props, ctx) { }, });
vue3需要用到的东西要从vue中解构出来import {defineComponent} from ‘vue’
通过export default导出,调用defineComponent()方法export default defineComponent
传入一个对象的参数,这个对象就是组件的配置对象,组件名称name:‘Home’,接收父组件的数据props:{},定义子组件components:{}, setup(){return{}},
最重要的是setup函数,最终return一个对象,setup中传入两个参数接收父组件的数据props和上下文ctx
===============================================================
1:在views底下新建父组件Home.vue
Home.vue
<template> <div> <nav-header></nav-header> <nav-main></nav-main> <nav-footer></nav-footer> </div> </template> <script> import NavHeader from "@/components/navHeader/NavHeader.vue"; import NavMain from "@/components/navMain/NavMain.vue"; import NavFooter from "@/components/navFooter/NavFooter.vue"; import { defineComponent} from "vue"; export default defineComponent({ name: "Home", props: {}, components: { NavHeader, NavMain, NavFooter, }, setup(props, ctx) { }, }); // 组件内容在script标签中定义 // 定义组件defineComponent // vue3需要用到的东西要从vue中解构出来 import {defineComponent} from 'vue' // 通过export default导出,调用defineComponent()方法 export default defineComponent // 传入一个对象的参数,这个对象就是组件的配置对象,组件名称name:'Home', 接收父组件的数据props:{}, 定义子组件components:{}, setup(){return{}}, // 最重要的是setup函数,最终return一个对象,setup中传入两个参数接收父组件的数据props和上下文ctx </script> <style> </style>
2:在components中创建三个文件夹,文件夹下分别创建文件
三个子组件navheader,navmain,navfooter
NavFooter.vue
<template> <div> footer </div> </template> <script> export default ({ }) </script> <style scoped> </style>
NavHeader.vue
<template> <div> header </div> </template> <script> export default ({ }) </script> <style scoped> </style>
NavMain.vue
<template> <div> main </div> </template> <script> export default ({ }) </script> <style scoped> </style>
3:app.vue 需要修改
<template> <img alt="Vue logo" src="./assets/logo.png"> <!-- <HelloWorld msg="Welcome to Your Vue.js App"/> --> <HomeView /> </template> <script> import HelloWorld from './components/HelloWorld.vue' import HomeView from './views/Home.vue' export default { name: 'App', components: { HelloWorld, HomeView } } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
运行