vue单组件与路由

引入Vue的两种方法

1.script直接引用

把vue.js下载到本地文件中,直接script引用。vue.js中定义了function Vue (options){…},所以在引入了vue.js的html文件中的script可以new一个Vue的实例。

<!DOCTYPE html>
<html lang="zh-vn">
<head>
    <meta charset="UTF-8">
    <title>18.1</title>
</head>
<body>
<div id="app">
    <div>
        <input type="text" v-model="name">
        <span v-show="name">我的名字是{{name}}</span>
    </div>
    <div>
        <input type="text" v-model="age">
        <span v-show="age">我的性别是{{age}}</span>
    </div>
</div>
<script src="../lib/vue.js"></script>
<script>
    var app=new Vue({
        el:"#app",//el选项表示该实例挂载到id为app的div上
        data:{//数据
            name:'A',
            age:'male'
        }
    })
</script>
</body>
</html>

2. Vue-cli搭建的项目

这种比较简单,一般大的项目都用vue-cli脚手架搭建一个vue项目。根据官网教程,我搭建了一个项目目录如下。使用了webpack模板,官网说明如下网站
http://vuejs-templates.github.io/webpack/
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

组件的结构

第一种是基于浏览器的开发方式,第二种是基于命令行的开发方式。命令行开发模式为我们带来了组件发开发方式。也就是说,用命令行方式开发其实开发的是vue各种各样的组件,我们拼装这些组件形成页面。所有的组件都被放在components文件夹下。
【组件的格式】
template
script
style

重要的文件

index.html:首页入口文件
src:这里是我们要开发的目录,基本上要做的事情都在这个目录里。里面包含了几个目录及文件:

  • assets文件夹: 放置一些图片,如logo等
  • components文件夹:该目录里存放的我们的开发文件组件,主要的开发文件都存放在这里了
  • router文件夹:路由配置目录
  • App.vue:整个项目的最原始的根组件
  • main.js:项目的入口文件

分析

先看index.html,首页入口文件。div中不要修改,会修改的只有该文件的头部

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>travel</title>
  </head>
  <body>
  <!--我们所有的组件所有的处理都是在这个id=app里动态渲染的,不要改-->
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

先看main.js 项目的入口文件

// 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',//此处挂载的是index.html(首页入口文件)中的id为app的div
  router,
  components: { App },//组件
  template: '<App/>'//模板,优先级高于outerHTML,所以显示模板内容,该模板只有一个APP组件
})

所以打开该App组件,.vue文件就是一个单文件组件

<!--模板在<template>-->
<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-view/>
  </div>
</template>
<!--逻辑在<script>-->
<script>
export default {
  name: 'App'
}
</script>
<!--样式在<style>-->
<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>

运行该项目,效果图如下
在这里插入图片描述
刚才分析main.js的模板中只有一个App组件,所以显示的内容是App组件里的内容。看图可以看出上面是一个图片,下面一堆文字。如果把图片以及样式都删掉,如下代码

<template>
  <div id="app">
    <router-view/><!--只剩下这个-->
  </div>
</template>
<script>
export default {
  name: 'App'
}
</script>
<style>
</style>

得到效果图:
在这里插入图片描述
那保留下来的内容其实就是< router-view/ >
其实< router-view/ >显示的就是当前路由地址所对应的内容
到页面上看,当前的路由就是 http://localhost:8081/#/ localhost下面的根路径
那么为什么这个路由对应的是上面图片的内容。就要回头去看main.js

// 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'//入口中这里引用了router

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,//创建根实例时引用了router变量 其实此处原写法为router:router,ES6中键和值相同可以简写
  components: { App },
  template: '<App/>'
})

于是打开router文件夹查看,import了router,vue会去找当前目录下的router,会自动引入该文件夹下的index.js文件。打开index.js文件

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'//在src目录下的components下

Vue.use(Router)

export default new Router({//一组路由的配置项
  routes: [
    {
      path: '/',//访问根路径的时候,根路径对应的路由是HelloWord
      name: 'HelloWorld',
      component: HelloWorld
    }
  ]
})

于是到components文件夹下找,有HelloWord.vue。发现这也是一个单文件组件。看内容确实就是刚才留下的文字内容

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>Essential Links</h2>
    <ul>
      <li>
        <a
          href="https://vuejs.org"
          target="_blank"
        >
          Core Docs
        </a>
      </li>
      <li>
        <a
          href="https://forum.vuejs.org"
          target="_blank"
        >
          Forum
        </a>
      </li>
      <li>
        <a
          href="https://chat.vuejs.org"
          target="_blank"
        >
          Community Chat
        </a>
      </li>
      <li>
        <a
          href="https://twitter.com/vuejs"
          target="_blank"
        >
          Twitter
        </a>
      </li>
      <br>
      <li>
        <a
          href="http://vuejs-templates.github.io/webpack/"
          target="_blank"
        >
          Docs for This Template
        </a>
      </li>
    </ul>
    <h2>Ecosystem</h2>
    <ul>
      <li>
        <a
          href="http://router.vuejs.org/"
          target="_blank"
        >
          vue-router
        </a>
      </li>
      <li>
        <a
          href="http://vuex.vuejs.org/"
          target="_blank"
        >
          vuex
        </a>
      </li>
      <li>
        <a
          href="http://vue-loader.vuejs.org/"
          target="_blank"
        >
          vue-loader
        </a>
      </li>
      <li>
        <a
          href="https://github.com/vuejs/awesome-vue"
          target="_blank"
        >
          awesome-vue
        </a>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

我把这个组件里的内容去掉,添加上自己的。

<template>
 <div>hello world</div>
</template>

<script>
export default {
  name: 'HelloWorld',
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

果然,页面上显示的我设置的内容
在这里插入图片描述
回过头来看。知道路由的配置都放在router文件夹下的index.js里。App.vue是整个应用的根组件。在App.vue里< router-view/>所显示的内容就是当前路由地址所对应的内容。这个内容就在index.js里找其所对应的组件。
了解这个之后,就可以改写代码。希望根路径下显示的是主页,而不是Helloword组件,所以先删除components里面的Helloworld.vue. 新建一个Home文件夹,里面新建Home.vue

<template>
    <div>home</div>
</template>
<script>
    export default {
        name: "Home"
    }
</script>
<style scoped>
</style>

再改写router里的Index.js

import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home/Home'//引入Home

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',//根路径
      name: 'Home',
      component: Home//对应组件
    }
  ]
})

运行项目,效果如下
在这里插入图片描述
修改路由成功。如果想要增加一个/list路由。先再components下创建一个List/List.vue

<template>
    <div>list</div>
</template>

<script>
    export default {
        name: "List"
    }
</script>

<style scoped>

</style>

再改写index.js

import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home/Home'
import List from '@/components/List/List'//引入

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/list',//路由
      name: 'List',
      component: List
    }
  ]
})

这时候打开http://localhost:8081/#/list 如下图
在这里插入图片描述
这里就实现了路由
重新回顾一下,index.html是入口首页文件。main.js的vue实例中el挂载在index.html的id为app的div节点上。同时main.js有template选项,template优先级高于index.html里的outerHTML,所以显示的是main.js里的template选项。因为template选项里只有一个App组件。所以页面显示的是App.vue组件。这也就是整个项目的根组件。该根组件里有< router-view/>,即当前路由地址所对应的内容。
这就要从router文件夹中index.js中找路由配置,里面规定了路由与组件的关系。

路由跳转/生命周期

为了验证有路由的生命周期,我在Home.vue中做了些修改

<template>
  <div>
    <div>home</div>
    <router-link to="/list">列表页</router-link>
  </div>
</template>

提供一个跳转路由链接。如下图
在这里插入图片描述
点击链接即到达
在这里插入图片描述

【注意】
1.整个项目是一个vue的实例
2.每个页面或者每个组件是一个vuecomponent的实例。也可以说一个Vue实例(官网这么说的"组件是可复用的 Vue 实例,且带有一个名字"),只不过稍微有些不同:

组件的data是一个function,组件没有el挂载点这个选项。除了这两点,实际基本上可以将Vue实例与Vue组件等同于一个东西来看待。

随后在main.js中vue实例,App组件vuecomponent实例,Home组件vuecomponent实例及List组件vuecomponent实例中都加了生命周期8个钩子函数并打印出来。
打开页面后控制台结果如下
在这里插入图片描述
然后我通过link跳转到list页面
在这里插入图片描述
我这里没有做详细解释,在vue路由生命周期这篇中把console内容完善了一下,同时加了些说明。

其它

观察到其实跟组建是App.vue,因为APP.vue里有个< router-view />所以才根据路由显示内容。那如果我在App.vue中增加一个组件/一段代码,这个组件/代码会在所有页面上显示。如是我简单改变App.vue如下:

<template>
  <div id="app">
    <div class="welcome">welcome!</div>
    <router-view/>
  </div>
</template>


<script>
export default {
  name: 'App',
  beforeCreate: function () {//这些钩子函数是为了查看生命周期添加的
    console.group('app beforeCreate 创建前状态===============》');
    console.log("%c%s", "color:red" , "el     : " + this.$el); //undefined
    console.log("%c%s", "color:red","data   : " + this.$data); //undefined
    console.log("%c%s", "color:red","message: " + this.message)
  },
  created: function () {
    console.group('app 创建完毕状态===============》');
    console.log("%c%s", "color:red","el     : " + this.$el); //undefined
    console.log("%c%s", "color:red","data   : " + this.$data); //已被初始化
    console.log("%c%s", "color:red","message: " + this.message); //已被初始化
  },
  beforeMount: function () {
    console.group('app beforeMount 挂载前状态===============》');
    console.log("%c%s", "color:red","el     : " + (this.$el)); //已被初始化
    console.log(this.$el);
    console.log("%c%s", "color:red","data   : " + this.$data); //已被初始化
    console.log("%c%s", "color:red","message: " + this.message); //已被初始化
  },
  mounted: function () {
    console.group(' app mounted 挂载结束状态===============》');
    console.log("%c%s", "color:red","el     : " + this.$el); //已被初始化
    console.log(this.$el);
    console.log("%c%s", "color:red","data   : " + this.$data); //已被初始化
    console.log("%c%s", "color:red","message: " + this.message); //已被初始化
  },
  beforeUpdate: function () {
    console.group('app beforeUpdate 更新前状态===============》');
    console.log("%c%s", "color:red","el     : " + this.$el);
    console.log(this.$el);
    console.log("%c%s", "color:red","data   : " + this.$data);
    console.log("%c%s", "color:red","message: " + this.message);
  },
  updated: function () {
    console.group('app updated 更新完成状态===============》');
    console.log("%c%s", "color:red","el     : " + this.$el);
    console.log(this.$el);
    console.log("%c%s", "color:red","data   : " + this.$data);
    console.log("%c%s", "color:red","message: " + this.message);
  },
  beforeDestroy: function () {
    console.group('app beforeDestroy 销毁前状态===============》');
    console.log("%c%s", "color:red","el     : " + this.$el);
    console.log(this.$el);
    console.log("%c%s", "color:red","data   : " + this.$data);
    console.log("%c%s", "color:red","message: " + this.message);
  },
  destroyed: function () {
    console.group('app destroyed 销毁完成状态===============》');
    console.log("%c%s", "color:red","el     : " + this.$el);
    console.log(this.$el);
    console.log("%c%s", "color:red","data   : " + this.$data);
    console.log("%c%s", "color:red","message: " + this.message)
  }
}
</script>

<style>
  .welcome{
    font-size: 32px;
    color: blueviolet;
  }
</style>

得到效果如下
在这里插入图片描述
点击链接
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值