下面有一个小例子,我们先新建一个页面并同时导入vue和自己写的vue.js:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue.js</title>
<link rel="stylesheet" href="style.css">
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="vue-app">
<h1> Events</h1>
<button v-on:click="add(1)"> 涨一岁</button>
<button v-on:click="subtract(1)"> 减一岁</button>
<button v-on:dblclick="add(10)"> 涨十岁</button>
<button v-on:dblclick="subtract(10)"> 减十岁</button>
<p>my age is {{age}}</p><div id="canvas" v-on:mousemove="updateXY">
{{x}},{{y}}
</div>
</div>
<script src="app.js"></script>
</body>
</html>
vue.js:
- new Vue({
- el: "#vue-app",
- data: {
- age:'30',
- x:'0',
- y:'0'
- },
- methods:{
- add:function(inc){
- this.age+=inc;
- },
- subtract:function(inc){
- this.age-=inc;
- },
- updateXY:function(event){
- this.x=event.offsetX;
- this.y=event.offsetY;
- }
- }
- })
下面就是一些常用的方法以及参数解释
el:需要获取的元素 ,一般跟html中的根容器元素
data:用于数据的存储
methods:存储方法 {{demo()}}
获取当前对象的值 this.XX
data-binding:给属性绑定对应的值
v-text
v-html
v-show
v-if
v-else
v-else-if
v-for
v-on(缩写@)
v-bind(缩写:)
v-model
v-pre
v-cloak
v-once
事件:
<!-- 阻止单击事件继续传播 -->
<a v-on:click.stop="doThis"></a><!-- 提交事件不再重载页面 -->
<form v-on:submit.prevent="onSubmit"></form><!-- 修饰符可以串联 -->
<a v-on:click.stop.prevent="doThat"></a><!-- 只有修饰符 -->
<form v-on:submit.prevent></form><!-- 添加事件监听器时使用事件捕获模式 -->
<!-- 即元素自身触发的事件先在此处处理,然后才交由内部元素进行处理 -->
<div v-on:click.capture="doThis">...</div><!-- 只当在 event.target 是当前元素自身时触发处理函数 -->
<!-- 即事件不是从内部元素触发的 -->
<div v-on:click.self="doThat">...</div>
键盘事件:
.enter
.tab
.delete (捕获“删除”和“退格”键)
.esc
.space
.up
.down
.left
.right
双向绑定:
/input/显示
v-model :绑定输出data属性
计算属性:
computed
{{demo}}
计算属性相比methods更加优化性能
耗时大量搜索时才会使用
class 与 stlye动态绑定
v-bind:class="{com}"
data{com:"true"}
v-if 和 v-show的区别
前着直接消失代码,后着加了css隐藏属性,前端还是能看到
v- for
data:{demos:["Mario","luffy","yoshi"]}
<ul>
<li v-for:"demo in demos">
{{demo1}}
</li>
</ul>
data:{users:[{name:"henry",age:30},{name:"bucky",age:30},{name:"emily",age:30}])
<ul>
<li v-for:"user in users">
{{user.name}}
</li>
</ul>
<ul>
<li v-for:"(user,index) in users">
{{user.name}}
</li>
</ul>
<!-- div 使用v-for循环时会创建多个div,vue提供了template减少div创建 -->
<template v-for="(user,index) in users">
<div v- for ="(key,val) in user">
<p>{{key}} - {{val}}</p>
<div>
</template>
多个vue调用修改值
var one=new Vue
var two=new Vue
<!-- 直接使用one.name可以获取其中的值 -->
组件component:: data methods computed都可以在组件中实现
Vue.component("greeting",{
template:’
<p>{
{name}}这是一个模板
<button v-on:click="changeName">改名</button>
</p>‘
data:function(){//这里面是data是方法
retrun {
name:"鹿晗"
}
methods:{
changeName:function(){
this.name="Hery"
}
}
}
})
<greeting> 前端可以当标签使用
搭建脚手架让开发速度更加快速:
Node.js 下载地址:https://nodejs.org/en/download/
安装完成后,打开你的命令行输入如下命令,验证安装是否成功:
- node --version //成功的话输出类似:v10.6.0
- npm --version //成功的话输出类似:6.1.0
- npm install -g vue-cli
- vue init webpack my-project 、
- cd my-project
- npm install $ npm run dev
阻止生产消息
vue.config.productiontip = false
全局嵌套组件main.js
import Users from './Users'
Vue.component("users",Users);
局部嵌套组件app.vue
import Users from './Users'
components{
“users”:Users 或者直接Users
}
css 作用域:
scoped:作用当前vue文件
<style scoped></style>
属性传值props:
父向子:
父:绑定属性:<users v-bind:users="users"></users>
子:方法里调用:export default{
name:'users',
props:["users“], 第一种写法,但是不够严谨,最好的方式下面是官方方式
props:{
users:{
type:Array,
required:true
}
}
}
<!-- 传值:String number boolean
引用:array object
传值只会修改局部,引用会修改全部
-->
事件传值
子向父:
子页面通过方法:
<header v-on:changeTitle>头部</header>
methods:{
changeTitle:function(){
this.$emit("事件名",“传递值”) //注册事件
}
父页面接收:
<app-header v-on:"事件名"="updateTitle($event)">
methods:{
updateTitle(title){
this.title=title;
}
生命周期(钩子函数):
methods:{
alert("写在下面")
},
beforeCreate:function(){
alert("实例化之前要做的事情")
},
created:function(){
alert(“组件实例化完毕,但页面还未显示”)
},
beforeMount:function(){
alert("组件挂在前,页面仍未展示,但虚拟DOM已配置")
},
mounted:function:(){
alert("组件挂在后,此方法执行后,页面显示")
},
beforeUpdate:function(){
alert("组件更新前,页面仍未更新,但虚拟DOM已经配置")
},
updated:function(){
alert("组件更新,此方法执行后,页面显示")
},
beforDestory:function(){
alert("组件销毁钱")
},
destory:function(){
alert("组件销毁")
}
路由:
安装路由 :npm install vue-router --save-dev
安装完成重启项目: npm run dev
mian.js
引入路由:import VueRouter from 'vue-router'
使用路由:Vue.use(Vuerouter)
配置路由:
const router=new Vuerouter({
routes:[
{path:"/地址",component:Home}
],
mode:"history" //去掉初始访问路径的#
})
调用(阻止a标签重新加载):
<router-link to="地址" ></router-link>
修改router-link标签为别的标签
<router-link to="地址" tag=“div”></router-link>
点击不同的路由展示不同的内容:
<router-view></router-view>
如果用户输入错误跳转到指定页面:
{path:"/地址",redirect:'路径'}
name属性及跳转方法:
{path:"/地址",name="homeLink",component:Home}
<router-link :to="{name:'homeLink'}"></router-link>
methods:{
goToMenu(){
//跳转到上一次浏览的页面
this.$router.go(-1)
//指定跳转的地址
this.$router.replace('地址')
//指定跳转路由的名字下
this.$router.replace({name:'路由名'})
//通过push跳转 常用
this.$router.push('地址')
this.$router.push({name:'路由名'})
}
}
二级路由(children[])和三级路由(同道理):
{path:"/地址",name="homeLink",component:Home,children:[
{path:"/地址",name="名字",component:组件},
{path:"/地址",name="名字",component:组件}
]}
二级路由和三级路由想默认展示页面也是redirect
导航守卫(全局守卫)
main.js <!-- to 进入哪一个路由,from离开哪个路由,next函数 -->
router.beforeEach((to,from,next)=>{
if(to.path=='/login' || to.path=='/register'){
next();
}else{
alert('还没登录,请先登录');
next(‘login’);
}
})
router-view复用:
{path:"/地址",name="homeLink",components:{
default:默认展示路径,
'调用名字':组件
}}
路由抽离:
新建js
import 组件名 from '组件地址' 引入组件信息。
const router={。。。}
其他页面使用:
import {调用名} from 'js地址'
const router=new Vuerouter({
调用名,
mode:"history"
})
滚动行为:
const router=new Vuerouter({
routes,
mode:"history",
scrollBehavior(to,from,savedPosition){ savedPosition//前进后退按钮触发
return {x:0,y:100}
return {select:'.btn'}
if(savedPosition){
return savedPosition
}else{
return {x:0,y:0}
}
}
})
HTTP:
安装:npm install vue-resource --save-dev
引入:import VueResource from 'vue-resource'
使用网络接口数据:jsonplaceholder.typicode.com
created(){
this.$http.get("http://jsonplaceholder.typicode.com/users").then((data)>={
this.users=data.body;
})
}
实现跨域请求:
测试网址:http://www.thenewstep.cn/test/testToken.php
配置:config>inde.js
proxyTable: {
'/apis': {
target: 'http://api.xxxxxxxx.com', //接口域名
changeOrigin: true, //是否跨域
pathRewrite: {
'^/apis': '' //需要rewritec重写的
}
}
}1.fetch
created(){
fetch("/apis/test/testToken.php",{
method:"post",
headers:{
token:"fec902c9ae5a2a9d8f84868ad064e706"
},
body:JSON.stringify({username:"Heigluck",password:"213123"})})
.then(result=>{
return result.json()
})
.then(data=>{
console.log(data)
})
}
2.axios
cnpm install axios 安装
main.js 全局引入
import axios from 'axios'
Vue.prototype.$axios = axios
axios.defaults.headers.common['token' = "fec902c9ae5a2a9d8f84868ad064e706"
axios.defaults.headers.post["Content-type"] = "application/json"
使用:
created(){
this.$axios.post("/apis/test/testToken.php",{username:"Heigluck",password:"213123"}).then(data=>{
console.log(data)
})
}