关于新建Vue项目的组件结构理解

项目结构

在这里插入图片描述
在这里插入图片描述

main.js

main.js是vue项目的人口,就好比Java的main函数一样。

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'


Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

上面代码的解释如下:

  • router:是router:router的缩写(在key/value相同时可以只写一个)
  • components:也是缩写components:{App:App}

components:{App:App}App是通过import导入的依赖

点击查看import和export default之间的关系

import App from './App'
App.vue代码
<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'App'
}


</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>

该文件由三部分构成<template>js代码css样式其中export default的作用就是将这个模板抛出

componentstemplate都是创建组件,它们的区别通过下面一个例子了解一下:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Vue</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>
  <body>
    <div id="app-1">
      <my-lable1></my-lable1>
      <my-lable2></my-lable2>
    </div>
    <div id="app-2"></div>
  </body>
  <script>
    /*全局组件*/
    Vue.component("my-lable1",{
      template:"<h1>Lable 1</h1>"
    });
    var ComponentA={
      template: "<h1>Lable 2</h1>"
    };
    new Vue({
      el: "#app-1",
      /*局部组件*/
      components:{
        "my-lable2":ComponentA
      }
    });
    new Vue({
      el:"#app-2",
      template:'<h1>h3</h1>'
    })
  </script>
</html>

在这里插入图片描述
由上图可以总结出:

  • component:在div容器中写自定义的组件
  • template:不需要写自定义的标签直接覆盖div容器

因此template:'<App/>'是使用自定义的组件去覆盖index.html中的div


上面App.vue<router-view>好比占位符,根据不同的路由显示不同的组件。

main.js中的router缩写router:routerrouterimport导入进来的。

import router from './router'

导入的时候文件夹下的文件后缀是.js是可以省略的,如果文件名是index,index也是可以省略

点进index.js文件


import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path:"/hello",
      name:"Fern",
      component:Fern
    }
  ]
})

router是路由,根据请求的路径响应对应的组件

  • 请求路径为:http://localhost:8080/#/
    在这里插入图片描述

  • 请求路径:http://localhost:8080/#/hello
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_35953966/article/details/104681089