初识Vue(二)
- 目标是先做一个完成登录的基本功能, 本文仅仅对登录页面归纳了一些需要完成的功能, 同时探究了Vue工程目录下, 各个文件如何协调运转以及插件如何使用.
登录页面设想
-
登录页样式(HTML)
-
登录页美化(CSS)
-
没有登录信息token, 重定向到登录页面
-
登录用户名, 密码预校验
-
校验通过发送异步请求到后台
-
请求通过跳转home页面
-
请求不通过弹窗提示
-
运行逻辑
- App.vue
- index.html
- main.js
![image-20200820091939995](https://i-blog.csdnimg.cn/blog_migrate/1f66fd93a8643b561bba9383e8d41619.png)
index.html 是我们最先进入的主页. 其中有一个id = "app"的div文件, 表示这是Vue根实例的挂载点. 也就是说Vue将完全掌握html这个div.
- index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>主页</title>
</head>
<body>
<div id="app"></div>
<!-- vue实例挂载点 -->
</body>
</html>
- main.js
官方文档: public/index.html` 文件是一个会被 html-webpack-plugin 处理的模板。在构建过程中,资源链接会被自动注入。
当我们编译运行时, main.js会被自动注入, 不需要手动在index.html关联js文件
main.js 代码
import Vue from 'vue'
import App from './App.vue' //导入App.vue
import router from './router'
import './plugins/element.js'
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App)
}).$mount('#app') // 挂载App.vue到index.html的div
- App.vue
最终页面会渲染template里的代码
<template>
<div>
hello
</div>
</template>
<script>
</script>
<style>
</style>
路由逻辑
- 首先我们做的其实是一个单页面应用, 本质上只有一个页面App.vue, 而且其他的页面都是利用Vue路由规则来跳转, 而不是请求
App.vue
- router-view作为一个路由占位符, 将被配置好的页面(组件)替换
<template>
<div>
<!-- 路由占位符-->
<router-view></router-view>
</div>
</template>
- 为了实现这个替换功能, 我们还需要进行路由绑定
router/index.js下
1. 导入Login.vue
2. 将’"/" "/login"路径都路由到Login组件
import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login'
Vue.use(VueRouter)
const routes = [
{ path: '/', redirect: '/login' }, //重定向
{ path: '/login', component: Login }, // 绑定路由和组件
]
const router = new VueRouter({
routes
})
export default router
- 设置Login组件导出
加入export default即可, 如下所示
<template>
<div>
<h1>Login组件</h1>
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
- 最终效果
![image-20200820111134519](https://i-blog.csdnimg.cn/blog_migrate/19abb0edf8c19c1fead8f5993245e5aa.png)
使用插件
- 为了便于上手, 这里使用了ElementUI插件, 基本是上开箱即用.
plugins/element.js
import Vue from 'vue'
import { Button } from 'element-ui' //导入某个组件, 这里是Button
Vue.use(Button) // 安装Button
这样就可以正常使用了 比如:
<template>
<div>
<el-button>Login组件</el-button> // 使用el-button
</div>
</template>