Vue快速入门的简单介绍
随着技术的发展,对于前端也有了一套属于他们的春天,,对于前端地位的上升独立的拿出来一个岗位来让前端人员站稳脚底,.,.对于前端技术的迭代速度让人窒息,真实太快太多的东西要了解,,就是对于纯前端的人来说有些技术都不一定知道,而我们作为一名合格的后台开发者,,,全栈全栈全干。多多少少也要了解一二,组件开发真有一天成为了主力军,我们也有招架的余力。。。话不多说,直接捶。。。。
帮助和拓展:Vue官方教程 ,,ElementUI官网,,,LayUI官网,,易用简洁且高效的http库axios
使用脚手架之前必须安装node.js —> Nodejs官网
一. 第一个vue-cli程序
准备工作
1 .安装Node.js的淘宝镜像加速器(cnpm)
# - g 就是全局安装
npm insatall cnpm -g
2 .安装 vue-cli
cnpm install vue-cli -g
# 测试是否安装成功
# 有6中模板, 我们通常使用webpack 因为能把我们的ES6 编译成ES5 降级
vue list
3. 选择一个自己写vue的工作地
# hello-vue 是项目名, 可以根据自己的选择
vue init webpack hello-vue
说明:
- Project name:项目名称,默认 回车 即可
- Project description:项目描述,默认 回车 即可
- Author:项目作者,默认 回车 即可 Install vue-router:是否安装 vue-router,选择 n
不安装(后期需要再手动添加) - Use ESLint to lint your code:是否使用 ESLint 做代码检查,选择 n
不安装(后期需要再手动添加) - Set up unit tests:单元测试相关,选择 n 不安装(后期需要再手动添加)
- Setup e2e tests with Nightwatch:单元测试相关,选择 n 不安装(后期需要再手动添加)
- Should we run npm install for you after the project has been created:创建完成后直接初始化,选择 n,我们手动执行;运行结果!
成功之后 可以根据提示来进行,,,启动成功,,访问 http://localhost:8080 就有显示效果了。
介绍一下结构
src 目录
目录是项目的源码目录,所有代码都会写在这里
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'
Vue.config.productionTip = false;
/* eslint-disable no-new */
new Vue({
el: '#app',
components: { App },
template: '<App/>'
});
-
import Vue from ‘vue’:ES6 写法,会被转换成 require(“vue”); (require 是 NodeJS 提供的模块加载器)
-
import App from ‘./App’:意思同上,但是指定了查找路径,./ 为当前目录
-
Vue.config.productionTip = false:关闭浏览器控制台关于环境的相关提示
-
new Vue({…}):实例化 Vue
- el: ‘#app’:查找 index.html 中 id 为 app 的元素
- template: ‘’:模板,会将 index.html 中 替换为
- components: { App }:引入组件,使用的是 import App from ‘./App’ 定义的 App 组件;
** App.vue**
<template>
<div id="app">
<img src="./assets/logo.png">
<HelloWorld/>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld'
export default {
name: 'App',
components: {
HelloWorld
}
}
</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:HTML 代码模板,会替换 中的内容
-
import HelloWorld from ‘./components/HelloWorld’:引入 HelloWorld 组件,用于替换 template 中的
-
export default{…}:导出 NodeJS 对象,作用是可以通过 import 关键字导入
- name: ‘App’:定义组件的名称
- components: { HelloWorld }:定义子组件
在hello,Vue中,关于 < style scoped> 的说明:CSS 样式仅在当前组件有效,声明了样式的作用域,是当前的界面私有的!
二. 这就开始搞起来了
还是原来的套路,,只不过在cmd中就把项目要的东西搞起来了,,整个elementUI耍耍。
如果使用idea 则需要下载一个vue插件重启了就可以 new 一个 Vue Component
使用 vue init webpack myvue 创建一个项目
安装 vue-router、element-ui、sass-loader 和 node-sass 四个插件
# 进入工程目录
cd myvue
# 安装 vue-router
npm install vue-router --save-dev
# 安装 element-ui
npm i element-ui -S
# 安装依赖
npm install
# 安装SASS 加速器
************************ *****************************
# ***** 这里安装完了之后 可能运行项目时会报错 因为 sass版本太高了 需要降级到 7.3.1 原本为 8.x..x.******
在 package.json 里修改 "sass-loader": "^7.3.1",
************************ ***********************************
cnpm install sass-loader node-sass --save-dev
# 启动测试
npm run dev
- assets:用于存放资源文件
- components:用于存放 Vue 功能组件
- views:用于存放 Vue 视图组件
- router:用于存放 vue-router 配置
在views目录下创建一个Login.vue 这是elementUI上的 可以直接拷贝过来
<template>
<div>
<el-form ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box">
<h3 class="login-title">欢迎登录</h3>
<el-form-item label="账号" prop="username">
<el-input type="text" placeholder="请输入账号" v-model="form.username"/>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input type="password" placeholder="请输入密码" v-model="form.password"/>
</el-form-item>
<el-form-item>
<el-button type="primary" v-on:click="onSubmit('loginForm')">登录</el-button>
</el-form-item>
</el-form>
<el-dialog
title="温馨提示"
:visible.sync="dialogVisible"
width="30%"
:before-close="handleClose">
<span>请输入账号和密码</span>
<span slot="footer" class="dialog-footer">
<el-button type="primary" @click="dialogVisible = false">确 定</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
export default {
name: "Login",
data() {
return {
form: {
username: '',
password: ''
},
// 表单验证,需要在 el-form-item 元素中增加 prop 属性
rules: {
username: [
{required: true, message: '账号不可为空', trigger: 'blur'}
],
password: [
{required: true, message: '密码不可为空', trigger: 'blur'}
]
},
// 对话框显示和隐藏
dialogVisible: false
}
},
methods: {
onSubmit(formName) {
// 为表单绑定验证功能
this.$refs[formName].validate((valid) => {
if (valid) {
// 使用 vue-router 路由到指定页面,该方式称之为编程式导航
this.$router.push("/main");
} else {
this.dialogVisible = true;
return false;
}
});
}
}
}
</script>
<style lang="scss" scoped>
.login-box {
border: 1px solid #DCDFE6;
width: 350px;
margin: 180px auto;
padding: 35px 35px 15px 35px;
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
box-shadow: 0 0 25px #909399;
}
.login-title {
text-align: center;
margin: 0 auto 40px auto;
color: #303133;
}
</style>
在 views 目录 中 创建一个 Main.vue
<template>
<div>
首页
</div>
</template>
<script>
export default {
name: "Main"
}
</script>
<style scoped>
</style>
创建路由,,在router目录下创建 index.js 的vue-router路由配置文件
import Vue from 'vue'
import Router from 'vue-router'
import Login from "../views/Login"
import Main from '../views/Main'
Vue.use(Router);
export default new Router({
routes: [
{
// 登录页
path: '/login',
name: 'Login',
component: Login
},
{
// 首页
path: '/main',
name: 'Main',
component: Main
}
]
});
配置路由,,修改main.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import router from './router'
// 导入 ElementUI
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import App from './App'
// 安装路由
Vue.use(VueRouter);
// 安装 ElementUI
Vue.use(ElementUI);
new Vue({
el: '#app',
// 启用路由
router,
// 启用 ElementUI
render: h => h(App)
});
App.vue
<template>
<div id="app">
<router-view />
</div>
</template>
<script>
export default {
name: 'App',
}
</script>
这样就可以运行测试了 。。。 在浏览器输入 localhost:8080/login
三. 路由嵌套
嵌套路由又称子路由,在实际应用中,通常由多层嵌套的组件组合而成。同样地,URL 中各段动态路径也按某种结构对应嵌套的各层组件
1. 在views里创建一个user文件夹 创建一个 List.vue 一个 Profile.vue
Profile.vue:
<template>
<div>
<h1>profile</h1>
</div>
</template>
<script>
export default {
name: "UserProfile",
}
</script>
<style scoped>
</style>
List.vue:
<template>
<h1>list</h1>
</template>
<script>
export default {
name: "UserList"
}
</script>
<style scoped>
</style>
2. 配置嵌套路由修改 router 目录下的 index.js 路由配置文件
使用 children 数组来配置
import Vue from 'vue'
import Router from 'vue-router'
import Login from "../views/Login";
import Main from "../views/Main";
import UserProfile from "../views/user/Profile";
import UserList from "../views/user/List";
import NotFound from "../views/NotFound";
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/login',
component: Login
},
{
path: '/main',
component: Main,
children: [ // 路由嵌套
{path: '/user/profile/:id', name: 'UserProfile' ,component: UserProfile},
{path: '/user/list', component: UserList}
]
}
]
});
3. 修改 Main.vue 组件
<template>
<div>
<el-container>
<el-aside width="200px">
<el-menu :default-openeds="['1']">
<el-submenu index="1">
<template slot="title"><i class="el-icon-caret-right"></i>用户管理</template>
<el-menu-item-group>
<el-menu-item index="1-1">
<router-link to="/user/profile">个人信息</router-link>
</el-menu-item>
<el-menu-item index="1-2">
<router-link to="/user/list">用户列表</router-link>
</el-menu-item>
</el-menu-item-group>
</el-submenu>
<el-submenu index="2">
<template slot="title"><i class="el-icon-caret-right"></i>内容管理</template>
<el-menu-item-group>
<el-menu-item index="2-1">分类管理</el-menu-item>
<el-menu-item index="2-2">内容列表</el-menu-item>
</el-menu-item-group>
</el-submenu>
</el-menu>
</el-aside>
<el-container>
<el-header style="text-align: right; font-size: 12px">
<el-dropdown>
<i class="el-icon-setting" style="margin-right: 15px"></i>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>个人信息</el-dropdown-item>
<el-dropdown-item>退出登录</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</el-header>
<el-main>
<router-view />
</el-main>
</el-container>
</el-container>
</div>
</template>
<script>
export default {
name: "Main"
}
</script>
<style scoped lang="scss">
.el-header {
background-color: #B3C0D1;
color: #333;
line-height: 60px;
}
.el-aside {
color: #333;
}
</style>
4. 路由模式有两种
- hash:路径带 # 符号,如 http://localhost/#/login
- history:路径不带 # 符号,如 http://localhost/login
修改路由配置,如下:
export default new Router({
mode: 'history',
routes: [
]
});
处理 404 创建一个名为 NotFound.vue 的视图组件,代码如下:
<template>
<h1>您访问的页面走丢了</h1>
</template>
<script>
export default {
name: "NotFound"
}
</script>
<style scoped>
</style>
修改路由配置,代码如下:
import NotFound from '../views/NotFound'
{
path: '*',
component: NotFound
}
四. 参数传递
- 可以在路由设置的时候在 path 属性中 介入 :id 占位符 (名字跟随自己)
{path: '/user/profile/:id', name:'UserProfile', component: UserProfile}
- 传递参数
我们就需要在传递参数的时候 进行 v-bind:to 绑定 也可以简写 为 :to name属性要和路由中的name一致,,
<router-link :to="{name: 'UserProfile', params: {id: 1}}">个人信息</router-link>
- 接收参数,必须在节点之内 不能单独
{{ $route.params.id }}
也可以使用 props 的方式
- 在修改路由设置的时候 ,加入 props: true
{path: '/user/profile/:id', name:'UserProfile', component: UserProfile, props: true}
- 参数传递的 和之前一样就可以
- 接收参数的时候 要在目标组件增加props属性
<template>
<div>
个人信息
{{ id }}
</div>
</template>
<script>
export default {
props: ['id'],
name: "UserProfile"
}
</script>
<style scoped>
</style>
五. 组件重定向
这里面也有的重定向 只需要在定义 path 的时候 只需要 加一个 redirect 就可以了
{
path: '/main',
name: 'Main',
component: Main
},
{
path: '/goHome',
redirect: '/main'
}
六. 路由钩子和异步请求
beforeRouteEnter:在进入路由前执行
beforeRouteLeave:在离开路由前执行
beforeRouteEnter:(to,from,next)=>{
// 路有钩子 进入离开等等 在里面可以使用异步请求 Axios
// 但必须要 next() 不然就不会往下走了
console.log("进入之前");
next();
},
beforeRouteLeave:(to,from,next)=>{
console.log("进入之后");
next();
}
参数:
- to:路由将要跳转的路径信息
- from:路径跳转前的路径信息
- next:路由的控制参数
- next() 跳入下一个页面
- next(’/path’) 改变路由的跳转方向,使其跳到另一个路由
- next(false) 返回原来的页面
- next((vm)=>{}) 仅在 beforeRouteEnter 中可用,vm 是组件实例
使用异步请求必须
- 安装Axios
cnpm install axios -s
- 在 main.js 中引用 axios
import axios from 'axios'
Vue.prototype.axios = axios;
- static 目录下的文件 是可以被访问到的 可以吧静态文件放在里面。。
- 在 beforeRouteEnter 中进行异步请求
export default {
props: ['id'],
name: "UserProfile",
beforeRouteEnter: (to, from, next) => {
console.log("准备进入个人信息页");
// 注意,一定要在 next 中请求,因为该方法调用时 Vue 实例还没有创建,
// 此时无法获取到 this 对象,在这里使用官方提供的回调函数拿到当前实例
next(vm => {
vm.getData();
});
},
beforeRouteLeave: (to, from, next) => {
console.log("准备离开个人信息页");
next();
},
methods: {
getData: function () {
this.axios({
method: 'get',
url: 'http://localhost:8080/static/mock/data.json'
}).then(function (repos) {
console.log(repos);
}).catch(function (error) {
console.log(error);
});
}
}
}