Vue.js
vue.js介绍
Vue是一套用于构建用户界面的渐进式框架。与其它大型框架不同的是,Vue 被设计为可以自底向上逐层应用。Vue 的核心库只关注视图层,不仅易于上手,还便于与第三方库或既有项目整合。另一方面,当与现代化的工具链以及各种支持类库结合使用时,Vue 也完全能够为复杂的单页应用提供驱动。
第一个Vue的页面
el: 挂载点,作用是锁定一个标签,可以是id选择器#id,类选择器 .class 。作用的范围,是选择标签中的所有。双标签除了body都可以,推荐使用div标签,id选择器
data: 数据对像,用来数据改变{{}}中的值
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>vue</title>
</head>
<body>
<div id="app">
{{ message }}
</div>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var app = new Vue({
el:"#app", //挂载
data:{
message:"Hello"
}
})
</script>
</body>
</html>
Vue指令
v-text:
作用:只能解析文本,值会被替换,可以使用表达式拼接,无法解析标签
<body>
<div id="app">
<h2 v-text="message+'!'">vue</h2>
<h2 v-text="info">love</h2>
{{message}}vue
</div>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var app = new Vue({
el:"#app",
data:{
message:"hello!",
info:"you!"
}
})
</script>
</body>
v-html:
作用:解析文本,还可以解析html标签例如a标签等。
v-on:
作用:为元素绑定事件
v-show:
作用:根据真假切换元素的显示状态(操作样式 none)
v-if:
作用:根据表达值的真假,切换元素的显示和隐藏(操作dom元素),操作dom直接移除
v-bind:
作用:为元素绑定属性。可以简写成 :src :titile 等
<div id="app">
<!-- :class="{active:isActuve} : 表示active能不能存在取决于isActuve是不是true-->
<img width="300px" :src="imgSrc" :title="imgTitle"
:class="{active:isActuve}" @click="toggleActive">
</div>
<script>
var app = new Vue({
el:"#app",
data:{
imgSrc:"bg.jpg",
imgTitle:"图片",
isActuve:false
},
methods:{
toggleActive:function(){
this.isActuve=!this.isActuve; //取反
}
}
})
</script>
v-for:
作用:根据数据生成列表结构。
语法:v-for = “(item,index) in arr”, item:数组里的值,取值:{{item}},arr:对应的是定义的数组名称
v-model:
作用:获取和设置表单元素的值(双向数据绑定)。
解释:这里的input里如果修改了值,那么这个message也会修改,同样的如果message修改,表单也会。
<body>
<div id="app">
<input type="text" v-model="message" @keyup.enter="getM"/>
</div>
<script>
var app = new Vue({
el:"#app",
data:{
message:"hello",
},
methods:{
getM:function(){
alert(this.message);
}
}
})
</script>
</body>
computed:
计算属性:将计算结果缓存起来的属性(将行为转化成了静态的属性)类似与缓存的概念。
注意:methods,computed方法不能重名。
使用场景:在访问量大得时候可以考虑将这个额结果缓存起来,计算属性的特征就是为了将不经常变化的计算结果进行缓存,节约我们的系统开销
<body>
<div id="app">
<!--方法的调用-->
<p>currentTime1 : {{currentTime1()}}</p>
<!--属性的调用-->
<p>currentTime2 : {{currentTime2}}</p>
</div>
<script src="vue/vue.js"></script>
<script>
var app = new Vue({
el:"#app",
data:{
message:"1323"
},
methods: {
currentTime1: function(){
return Date.now(); //获得一个时间戳
}
},
computed: {
currentTime2: function(){
return Date.now();
}
}
})
</script>
</body>
component(组件):
插槽:自定义空模板,相当于占位符
props:定义需要传的参数名
<div id="app">
<ul>
<todo v-for="item in arrs" v-bind:msg="item"></todo>
</ul>
</div>
<script src="vue/vue.js"></script>
<script>
//注册组件 todo:自定义标签名, props的参数要和template的属性绑定。
Vue.component("todo",{
props:['msg'],
template: '<li>{{msg}}</li>'
})
var app = new Vue({
el:"#app",
data:{
arrs:['张三','李四','王五']
}
})
</script>
vuejs项目创建操作
下载Nodejs:
Nodejs官网下载:http://nodejs.cn/
下载过程:一直点下一步就行了
npm基本命令
#更新至指定版本
npm install npm@6.14.5 -g
#更新至最新版
npm install -g npm
#node版本管理nvm 通过代理翻墙下载安装
curl --proxy 127.0.0.1:1087-o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash
1、安装cnpm
# -g 全局安装
npm install cnpm -g
# 淘宝的镜像地址
npm install -g cnpm --registry=https://registry.npm.taobao.org
1.1、安装失败
# 设置一个镜像
npm config set registry https://registry.npm.taobao.org
# 查看是否设置成功
npm config get registry
# 再次安装cnpm
npm install cnpm -g
1.2、查看版本
# 查看node版本
node -v
# 查看npm版本
npm -v
1.3、安装vue-cli
# 旧版
cnpm install vue-cli -g
# 新版 3.0以上
npm install -g @vue/cli
# 升级vue
cnpm i -g @vue/cli
# 指定版本安装
npm install -g @vue/cli@3.12.1
# 查看安装是否成功
vue list
vue --version
vue -V
1.4、卸载vue-cli
npm uninstall -g @vue/cli
1.5、安装出错
# 执行三步
npm i npm -g
npm i vue-cli -g
cnpm i vue-cli -g
2、初始化一个项目
cd进入一个路径然后输入vue init webpack firstvue
选项操作:
# 项目名
Project name :myvue
# 项目描述(可以不选择直接回车)
Project description (A Vue.js project)
# 作者
Author : kai
# 编译情况
Vue build (选择第一个就行,运行+编译)
# 是否安装vue-router(n)
Install vue-router? (Y/n) :n
# 是否使用ESlint(n)
Use ESLint to lint your code? :n
# 是否安装测试(n)
Set up unit tests (Y/n) : n
# 是否安装e2e测试 (n)
Setup e2e tests with Nightwatch? n
# 是否创建npm install(选第三个)
Should we run `npm install` for you after the project has been created? (recommended)
Yes, use NPM
Yes, use Yarn
> No, I will handle that myself
3、下载依赖
进入新创建的这个目录下输入命令:
npm install
4、启动服务
进入当前项目路径:将项目打包启动
npm run dev
启动成功后的状态:
停止服务:
ctrl+c
5、安装webpack
打包 :
npm install webpack -g
安装:
npm install webpack-cli -g
如果失败:可以用cnpm
测试安装成功:
webpack -v
webpack-cli -v
6、简单使用webpack
1、新建一个空项目
2、创建一个modules文件夹,下面创建hello.js模块,main.js程序入口
hello.js:
exports.sayHi = function () { //暴露接口
document.write("<h1>1233211234567</h1>")
}
main.js:
var hello = require("./hello"); //引入接口
hello.sayHi(); //调用接口中方法
3、创建一个webpack.config.js导入
module.exports = {
entry: './modules/main.js',
output: {
filename: "./js/bundle.js"
}
};
4、使用webpack命令将这个项目打包。
webpack --watch: 监听项目,打包不会结束,如果js有变化,会马上重新打包
5、打包成功会出现一个新的文件夹dist,下面就是打包后的js文件
6、调用js就行
vue-router路由
vue-router是什么?
router,即“路由”。路由是一个网络工程里面的术语。James F.Kurose,Keith W.Ross著.陈鸣译.《计算机网络》中有讲到
路由(routing)是指分组从源到目的地时,决定端到端路径的网络范围的进程
在WEB开发的世界里面,路由其实指的就是控制我们在浏览器中输入的URL应该走入哪个页面中的一个组件。
使用router
1、安装
npm install vue-router --save-dev
2、路由的用法
1.1、新建一个components文件夹,这个文件管理.vue的文件
1.2、创建Content.vue文件,用途:内容页
<template>
<h1>内容页</h1>
</template>
<script>
export default {
name: "Content"
}
</script>
<style scoped></style>
1.3、在src下创建router文件下,这个是放置路由的配置js文件
1.4、在router下创建index.js用来管理components下的.vue文件
import Vue from 'vue' // 导入vue的包
import VueRouter from 'vue-router' // 导入vue-route,路由的包
import Content from '../components/Content' // 导入自定义的Content内容页
//安装路由
Vue.use(VueRouter);
//配置导出路由
export default new VueRouter({
routes: [
{
//路由路径
path: '/content',
name: 'content',
//跳转的组件
component: Content
}
]
});
1.5、在主入口main.js下配置
import Vue from 'vue' //导入vue
import App from './App'
import router from './router' //自动扫描包下面的路由配置
Vue.config.productionTip = false
new Vue({
el: '#app',
//配置路由
router,
components: { App },
template: '<App/>'
})
Element-ui
安装element-ui:
npm i element-ui -S
安装SASS加载器
这里安装了两个,一个sass-loade ,一个node-sass
cnpm install sass-loader node-sass --save-dev
# 分开安装
npm install sass-loader --save
npm install node-sass --save;
//如果版本有问题就卸载重装
//卸载 node-sass
npm uninstall -g node-sass@4.14.1
//指定为4.几的
npm install node-sass@4.14.1
v-charts
npm i v-charts echarts -S
Npm命令解释
总结创建项目步骤
# 进入工程目录
cd 目录名
# (非必备)安装 SASS 加载器 。@7.3.1是指定版本,可以不加。
npm install sass-loader@7.3.1 node-sass --save-dev
# 安装 element-ui
npm i element-ui -S
# 安装 vue-router
npm install vue-router --save-dev
# 安装项目所有依赖
npm install
路由基本使用
嵌套路由
钩子函数
-
beforeRouteEnter :在进入路由前执行
-
beforeRouteLeave:在离开路由前执行
案例:
beforeRouteEnter:(to,from,next)=>{
console.log(to);
console.log(from);
console.log(next);
next();
},
beforeRouteLeave:(to,from,next)=>{
console.log(to);
console.log(from);
console.log(next);
next();
}
参数说明:
- to : 路由将要跳转的路径信息
- from:路径跳转前的路径信息
- next:路由的控制参数
- next() 跳入下一个页面
- next(’/path’) 改变路由的跳转方向,使其跳到另一个路由
- next(false) 返回原来的页面
- next((vm)==>{}) 仅在beforeRouteEnter 中可用 ,vm是组件实例
在钩子函数中使用异步请求(Axios)
axios普通导包
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
axios的使用
使用方法:get或post方法发送对应请求,then方法的回调函数是在请求成功或失败时触发。
1、使用get请求
<input type="button" value="get请求" class="get" />
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
//随机获取三条笑话
document.querySelector(".get").onclick = function(){
axios.get("https://autumnfish.cn/api/joke/list?num=6")
.then(function(data){
console.log(data);
},function(err){
console.log(err)
})
}
</script>
安装Axios
npm install axios -s
使用Axios
# 导入
import axios from 'axios'
# 设置全局调用
Vue.prototype.axios = axios;
异步使用
//定义一个方法
methods:{
getData:function () {
this.axios({
method:'get',
//异步请求,这个路径可以是后台的请求路径
url:'http://localhost:8080/data.json',
}).then(function (repos) {
console.log(repos);
}).catch(function (error) {
console.log(error);
});
}
}
//使用next((vm)==>{}) 方式调用定义的方法
beforeRouteEnter:(to,from,next)=>{
next((vm) => {
vm.getData();
});
},
注意:要在需要跳转的router中
案例:
<template>
<div>
会员等级:ID={{this.$route.params.id}}
</div>
</template>
<script>
export default {
name: "MemberLevel",
beforeRouteEnter:(to,from,next)=>{
next((vm) => {
vm.getData();
});
},
beforeRouteLeave:(to,from,next)=>{
next();
},
methods:{
getData:function () {
this.axios({
method:'get',
url:'http://localhost:8080/data.json',
}).then(function (repos) {
console.log(repos);
}).catch(function (error) {
console.log(error);
});
}
}
}
</script>
<style scoped>
</style>
Vuex
安装vuex
npm install vuex --save
使用vuex
在src下创建store文件存放vuex的配置
创建一个js文件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
//公共state对象,存储所有组件的状态
const state = {
user:{
name:''
}
}
//唯一取值的方法,计算属性
const getters={
getUser(state){
return state.user;
}
}
//唯一可以修改state值的方法,同步阻塞
const mutations={
updateUser(state,user){
state.user = user;
}
}
//异步调用mutations方法
const actions = {
asyncUpdateUser(context,user){
context.commit('updateUser',user);
}
}
//暴露
export default new Vuex.Store({
state,
getters,
mutations,
actions
});
main.js使用,使用方法和router一样
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import VueRouter from 'vue-router'
import router from './router'
import axios from 'axios'
import Vuex from 'vuex'
import store from './store'
Vue.use(VueRouter);
Vue.use(ElementUI);
Vue.use(Vuex);
//全局调用
Vue.prototype.axios = axios;
Vue.config.productionTip = false
router.beforeEach((to,form,next)=>{
let isLogin = window.sessionStorage.getItem('isLogin');
if(to.path == '/logout'){
window.sessionStorage.clear();
next('/login');
}else if(to.path == '/login'){
if(isLogin != null){
next('/main');
}
}else if(isLogin == null){
next('/login');
}
next();
});
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
怎么调用方法?
调用了asyncUpdateUser方法
this.$store.dispatch('asyncUpdateUser',{name:this.form.name});
什么是Vuex
Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。
如下图:
图1是没有使用vuex的,这时如果需要传递数据的话,则需要像链表一样,层层递进。
图2则是使用了vuex,将数据存放在一个STORE的组件中,在调用的时候则可以直接取到数据。
优点:
- 能够在Vuex中集中管理共享的数居,易于开发和后期维护
- 能够高效地实现组件之间的数据共享,提高开发效率
- 存储在vuex中的数据都是响应式的,能够实时保持数据与页面的同步
什么样的数据适合存储到Vuex中:
一般情况下,只有组件之间共享的数据,才有必要存储到vuex中;对于组件中的私有数据,依旧存储在组件自身的data中即可。
Store使用
Store方法介绍
State
作用:用于存放数据
Mutation
作用:用于变更Store中数据
1、只能通过mutations变更Store数据,不能直接操作store中的数据
2、通过这种方式虽然繁琐,但可以集中监控所有数据变化。
3、使用commit调用
Action:
作用:用于处理异步任务。
1、如果通过异步操作变更数据,必须通过Action,而不能使用Mutation,但是在Action中还是要通过触发Mutation的方式间接变更数据。
2、任何异步操作都只能在Action中完成
3、使用dispatch触发
Getter
作用:Getter用于对Store中的数据进行加工处理形成新的数据。
1、Getter可以对Store中已有的数据加工处理之后形成新数据,类似Vue的计算属性
2、Stroe中数据发生变化,Getter的数据也会跟着变化,类似响应式
语法:
1、 this.$store.getters.方法名
2、 impore {mapGetters} from 'vuex'
computed: {
...mapGettres(['方法名'])
}
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
add(state){
//变更状态
state.count++
},
//加N个数
addN(state, step) {
state.count += step
},
sub(state){
state.count--
},
subN(state, step){
state.count -= step
}
},
actions: {
// 异步延时器
addAsync(context){
setTimeout(()=>{
context.commit('add')
},1000)
},
addAsyncN(context,temp){
setTimeout(()=>{
context.commit('addN',temp)
},1000)
}
},
modules: {
},
// getters方法
getters: {
showNum(state) {
return '当前最新的数量是【'+state.count+'】'
}
}
})
main.js中引入store
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
store,
render: h => h(App)
}).$mount('#app')
例子:
案例: 计数器。
语法介绍:
this.$store.state.count : 调用store中state的count属性
commit: 第一种调用mutations某个方法
src/components/Additon.vue
<template>
<div>
<h3>当前count值为:{{this.$store.state.count}}</h3>
<button @click="btnHandler1">+1</button>
<button @click="btnHandler3">+1 Async</button>
<button @click="btnHandler4">+N Async</button>
</div>
</template>
<script>
export default {
name: 'Addition',
data() {
return {}
},
methods: {
btnHandler1(){
// 调用add不带参数
// this.$store.commit('add');
//调用 addN 带参数
// commit 的作用是用来调用mutation函数
this.$store.commit('addN',3)
},
//异步 自增+1
btnHandler3(){
// dispatch函数专门用来触发actions
this.$store.dispatch('addAsync')
},
btnHandler4(){
this.$store.dispatch('addAsyncN',2)
}
}
}
</script>
<style scoped>
</style>
src/components/Subtraction.vue
第二种调用mutations的方法:
1、按需引入import {mapState,mapMutations} from ‘vuex’
2、映射全局数据 …mapMutations([‘sub’,‘subN’]),
<template>
<div>
<!--<h3>当前count值为:{{count}}</h3>-->
<h3>当前count值为:{{showNum}}</h3>
<button @click="btnHandler1">-1</button>
<button @click="btnHandler2">-N</button>
</div>
</template>
<script>
// 从vuex中按需导入 mapState 函数
import {mapState,mapMutations,mapGetters} from 'vuex'
export default {
name: 'Subtraction',
data() {
return {}
},
computed: {
//...是展开运算符,把全局数据映射为当前组件的计算属性
...mapState(['count']),
...mapGetters(['showNum'])
},
methods: {
...mapMutations(['sub','subN']),
btnHandler1(){
this.sub();
},
btnHandler2() {
this.subN(3)
}
},
}
</script>
<style scoped>
</style>