Vue 常用语法指南
2017-07-06 本文已影响419人
fangtang0101
下面都是总结的 Vue 中常用语法,以便快速查找
1.绑定 style
<div class="experticon" :style="'background-image:url('+ value.touxiang + ');'"></div>
<div class="pic" :level="levelString" onclick="main_godoctor(event,8119);" v-bind:style="urlFain"></div>
下面的写在计算属性中
urlFain: function() {
if(this.urlicon) {
return 'background-image: url(' + this.urlicon + ')';
} else {
return 'background-image: url(' + '//7xlm05.com2.z0.glb.qiniucdn.com/o_1b4ipdasp162d2u118rm5ot1e3a9.png' + ')';
}
}
2.div 绑定 click事件
<div class="action-button like" @click="putzhan(value.bmStatus)">
3.v-if v-else 的用法
<span v-if="value.bmStatus" class="like-img-done"></span>
<span v-else class="like-img"></span>
4.获取路由的参数
var docId = this.$route.params.id;
5.Vue中的 http请求-用ajax也行
this.$http.post(apiurl, postData).then(function(response) {
var res = response.data;
console.log(res);
this.value.bmStatus = actionType;
}, function(response) {});
6.v-if if为真,那么下面的代码成立
<div class="comments" v-if="value.items.length > 0">
6.v-for
<Comment v-for="item in value.items" v-bind:value="item"></Comment>
7.v-html
<div v-html=value.htmlcontent></div>
8.路由跳转
this.$router.push({ name: 'doc', params: { id: docId }})
click: function(id) {
var toPath = '';
if(1 == id) {
toPath = '/projectPage/h5';
}
if(2 == id) {
toPath = '/projectPage/ios';
}
this.$router.push({
path: toPath
})
}
9.传值 观察者模式
http://taobaofed.org/blog/2016/11/17/react-components-communication/
在html处需要导入
最简单的如下
var eventMain;
// http://blog.csdn.net/magic__man/article/details/51831227
//添加监听 name funEvent 执行的函数
function addEvent(name, funEvent) {
// document.addEventListener('oneating', function (event) {
// alert(event.mingzi+','+event.message);
// }, false);
document.addEventListener(name,funEvent(event), false);
}
//发出事件 name 事件的名字 objc 事件传递的参数,为objc
function sendEvent(name, objc) {
var event = document.createEvent('HTMLEvents');
event.initEvent(name, true, true);
event.canshu = objc;
document.dispatchEvent(event);
}
var vmEvent ;
发送消息
<template>
<div class="list">
list one
<div @click='event()'>
传递参数 88 请点击
</div>
</div>
</template>
methods: {
event: function(e) {
sendEvent('list', 'message:传递信息,位置:listTwo');
}
}
接收消息,直接在生命周期的方法里面写 即可
mounted: function() {
catchEvent('list',function(event){
alert('接收到消息了,此处位于listTwo'+event.info);
})
}
10.Vue 简单传值 父子之间
在子组件里面加监听方法,一般都是 点击方法,因为方便eventEmit
<template>
<div class="list">
list one
<div @click='event()'>
传递参数 88 请点击
</div>
<div @click='eventEmit()'>
点击我 通过 emit 方法传递参数给 list(父组件)
</div>
</div>
</template>
methods: {
eventEmit: function() {
//注意此处的 eventEmit 不能错,参数也可传过去
this.$emit('eventEmit','message:这句话是通过$emit 传值过去的位置listOne');
}
},
在父组件中 通过v-on 绑定过去
<template>
<div class="list">
list 本页id
<h2>User {{ $route.params.id }}</h2>
<div @click='event(88)'>
传递参数
</div>
<ListOne v-on:eventEmit="eventEmitList"></ListOne>
<ListTwo></ListTwo>
</div>
</template>
methods: {
eventEmitList: function(msg) {
alert('通过emit 收到的消息list 参数为:'+msg);
}
},
10. class 绑定 filter
<div v-for="(item,index) in items">
<div v-bind:class="item | filterClass(index)">测试class{{index}}</div>
</div>
// 注意返回 是以 字符串拼接的 class 样式,中间加 空格
filterClass: function(val,index) {
console.log(val);
console.log(index);
if(index == 2){
return "red css_font";
}else{
return "";
}
},
11.全局filter 的添加
// filters.js
export function timeago(time) {
time = new Date(time);
var delta = parseInt((new Date() - time) / 1000, 10);
if (delta <= 0) return 'just now';
var minutes = delta / 60;
if (minutes < 1) return 'less than a minute ago';
if (minutes < 2) return 'about a minute ago';
var hours = minutes / 60;
if (hours < 1) return parseInt(minutes, 10) + ' minutes ago';
if (hours < 1.5) return 'about an hour ago';
var days = hours / 24;
if (days < 1) return Math.round(hours) + ' hours ago';
if (days < 7) return parseInt(days, 10) + ' days ago';
var month = time.getMonth() + 1;
if (month < 10) month = '0' + month;
var date = time.getDate();
if (date < 10) date = '0' + date;
return [time.getFullYear(), month, date].join('-');
}
//直接调用
import * as filters from './filters';
// register filters
Object.keys(filters).forEach(function(k) {
Vue.filter(k, filters[k]);
});
12.Vue 中动态绑定数据
// 生命周期方法
mounted: function() {
this.$set(this.stage,'age',2);
this.$set(this.stage,'form',{form_name:'my_form',id:20});
this.$set(this.stage.bind,'bind_obj',{bind_obj_name:'name====',id:34});
this.$set(this.stage.bind,'list_ceshi',[]);
},
changeAge(){
this.stage.age = 90;
this.stage.form = {form_name:'my_formpppppp',id:290000};
this.stage.bind.bind_obj = {bind_obj_name:'+++++',id:888};
this.stage.bind.list_ceshi.push({name:"ceshi----"});
}
98E0DE8C-B5BC-406B-B0A1-0E063FD51796.png
13.Vue 全局方法的设置
tool.js
import Vue from 'vue'
export default{
install(Vue,options)
{
Vue.prototype.getData = function (val) {
return val + '我是插件中的方法';
// console.log('我是插件中的方法');
}
// 全局变量 ,直接 this. 即可调用
Vue.prototype._name_my = 'fang chun gao ';
// 全局 filter 直接 {{stage |filtersrrr("uuu")}} 可以调用
Vue.filter('filtershiyan' , function(value) {
return '哈哈,方春高,这是全局的filter'
});
}
}
main.js
import tool from './tool';
Vue.use(tool)
使用
clickMethodAll(){
var str = 'yyyyy';
console.log(str);
str = this.getData(str);
console.log(str);
},
第二种方法
tool.js
export function toolsMethod(val) {
return '哈哈,我是全局方法返回的数据';
};
使用的地方 (不用写 this,区别在此),方法需要每一个导出
import { toolsMethod } from '../tool';
var str = 'yyyyy';
console.log(str);
str = toolsMethod(str);
console.log(str);
},
14.Vue Element 中面包屑 动态跳转
<el-breadcrumb separator="/">
<el-breadcrumb-item :to="my_path">首页</el-breadcrumb-item>
<el-breadcrumb-item >活动管理</el-breadcrumb-item>
<el-breadcrumb-item>活动列表</el-breadcrumb-item>
<el-breadcrumb-item>活动详情</el-breadcrumb-item>
</el-breadcrumb>
// data 中
my_path:{name: ''},
// 改变
this.my_path = {name:'serviceApply',params:{state_id:9359}}
15.Vue 中深拷贝
cloneObj: function (obj1) {
var obj={};
obj=JSON.parse(JSON.stringify(obj1));
return obj
}
16.Vue Element 或则说 v-on 父组件 拿到子组件的值,并且 方法中带入 父组件自己的参数
<el-select v-model="item.audit_type" placeholder="请选择"
@visible-change="changeVisible($event,index4,index)">
<el-option
v-for="option in Listaudit_type"
:key="item.value"
:label="option.label"
:disabled="option.disabled"
:value="option.value">
</el-option>
</el-select>
changeVisible(e,section,row){
if(e){
var mark = false; //不禁用
var item1 = this.audit_setting.items[section];
var item2 = item1.steps[row+1];
if(!this.isEmpty(item2) && item2.category == "member") mark = true;
this.Listaudit_type[0].disabled = mark;
}
}
17.Vue Resource 中 网路请求
1.发出2 个请求,两个请求都返回才会 继续下一步
- 发出两个请求 同时发出,但是,需要都返回才能 做下一步操作
解决办法
Promise 的 then 方法可以 链式 传递
this.$http.put(API.url+'stages/'+id_current,fd,
).then((res)=>{
// callBack(true);
// if(publish){
// this.$router.go(-1);
// this.$store.dispatch('get_type_service_add',0);
// }
return {abc:123}
this.hiddenLoading();
},(error)=>{
// this.showMessage("warning","请求出错");
// this.hiddenLoading();
callBack(false);
}).then((res)=>{
// 此处在上一个 then 执行完了 便顺序执行,(没有返回 res ,上一步返回 err 此处依旧执行)
if(res.abc == 123){
// 下一个网络请求
}
})
Promise 的 all 方法
// 生成一个Promise对象的数组
var promises = [2, 3, 5, 7, 11, 13].map(function (id) {
return getJSON('/post/' + id + ".json");
});
Promise.all(promises).then(function (posts) {
// ...
}).catch(function(reason){
// ...
});
var p1 = this.$http.put(API.url+'stages/'+id_current,fd,
).then((res)=>{
//xxx
},(error)=>{
// xx
})
var p2 = this.$http.put(API.url+'stages/'+id_current,fd,
).then((res)=>{
//xxx
},(error)=>{
// xx
})
var p = Promise.all([p1, p2]).then(function (posts) {
// ...
}).catch(function(reason){
// ...
});;
18.v-html 与 v-if 用方法代替,包括一切 v-xx
<span class="tips" :class="ticket_ji.content | filterTicketContent" v-html="sortTipsToHtmlGol(ticket_ji.content)"></span>
全局方法
// 将 备注中 的 回车 符号全部 转成 <br/>
Vue.prototype.sortTipsToHtmlGol = function (tipString) {
var res = '';
res = tipString.replace(/\n/g, "<br/>")
return res;
}
19.router(在当前页面 改变 地址栏中的参数,并且刷新)
//当前页面的路由就是 /system/serviceAdd/1,需要将 1变成 10,或则 增加 produceId 参数(场景)
// this.$router.go(0);刷新当前页面,相当于 按了 F5
this.$router.replace({
path: '/system/serviceAdd/1',
query:{
'produceId':2910,
'edit':0
}
})
this.$router.go(0);
18.正则表达式
var str = "123[备注&~!暂未符号&~!]哈哈阿萨德浪费,[备注&~!abc&~!]UN的咖啡馆";
var str_shi = '[备注&~!暂未符号&~!]'
var regexp_shi = new RegExp("\\[备注\\&\\~\\!(\\S*)\\&\\~\\!\\]",'i');
var rsb_shi = str_shi.match(regexp_shi);
// / 用 \\ 来代替
var regexp = new RegExp("\\[备注\\&\\~\\![^x00-xff]{0,}[\\w]{0,}\\&\\~\\!\\]",'g');
var rsb = str.match(regexp);
var listSub = [];
for(var i=0;i<rsb.length;i++){
var str1 = rsb[i];
var regexp_sub = new RegExp("\\[备注\\&\\~\\!(\\S*)\\&\\~\\!\\]",'i');
var rsb_sub = str1.match(regexp_sub);
if(!this.isEmptyGol(rsb_sub) && rsb_sub.length >1 )listSub.push(rsb_sub[1])
}
var rs = str.split(regexp);
return {a:rs,b:rsb,c:listSub};
结果:
image.png
18.Vuex 一个好用的插件
git 地址 https://github.com/robinvdvleuten/vuex-persistedstate
import Vue from 'vue'
import Vuex from 'vuex'
import admin from './modules/admin'
import editid from './modules/edit.js'
import department_zr from './modules/department.js'
import step from './modules/step.js'
import listscreen from './modules/listscreen.js'
import project from './modules/project'
import getters from './getters'
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex);
const store=new Vuex.Store({
modules:{department_zr,listscreen,editid,admin,step,project},
getters,
plugins:[createPersistedState({
key:'admin',
storage: window.sessionStorage
})]
})
export default store
//设置值
this.$store.dispatch('sendHasRoot',true);
//取值
computed:{
...mapGetters(["stepName","currentProject","userId","currentUser","hasJumpInApply","yearChange","changeProjectStatus"]),
项目中用法与结构
image.png
19.Vue-Router 的拦截 生命周期
beforeRouteEnter(to,from,next){
next(vm=>{
if(to.name=='serviceRight'){
vm.formInline = vm.formSearch
vm.formInline.provider_id_eq = to.params.id
vm.page = vm.formPage
vm.value1= vm.formInline.created_at_gteq
vm.value2= vm.formInline.created_at_lteq
vm.toSearch()
}
})
},
beforeRouteLeave(to,from,next){
var mark =false;
if(to.name=='serviceRight'||to.name=='formdetails'){
mark = true
}
if(!mark){
this.formInline = {
name_cont: '',
owner_eq: '',
category_eq: '',
service_id_eq: '',
created_at_gteq: '',
created_at_lteq: '',
provider_id_eq:'',
service_category_id_eq:''
},
this.page = 1
this.value1= ''
this.value2= ''
this.$store.dispatch('formSearch', this.formInline)
this.$store.dispatch('formPage', this.page)
}
next(true)
},
20.css动画
鼠标移入 放大效果
&:hover .img {
@include transform(scale(1.3));
-webkit-transition: 500ms;
-moz-transition: 500ms;
-ms-transition: 500ms;
-o-transition: 500ms;
transition: 500ms;
}
21.ES6 中数组与 对象的复制 方法(浅拷贝)
http://blog.csdn.net/zgrkaka/article/details/70792297
数组
this.nodeCurrent = this.ComouterSels[0].slice(0);
对象
this.modelCurrent = Object.assign({}, this.ComouterSels[0]);
22.formData 的传递
http://www.cnblogs.com/wonyun/p/7966967.html
function objectToFormData (obj, form, namespace) {
const fd = form || new FormData();
let formKey;
for(var property in obj) {
if(obj.hasOwnProperty(property)) {
let key = Array.isArray(obj) ? '[]' : `[${property}]`;
if(namespace) {
formKey = namespace + key;
} else {
formKey = property;
}
// if the property is an object, but not a File, use recursivity.
if(typeof obj[property] === 'object' && !(obj[property] instanceof File)) {
objectToFormData(obj[property], fd, formKey);
} else {
// if it's a string or a File object
fd.append(formKey, obj[property]);
}
}
}
return fd;
}
23.# [css3中user-select的用法详解]
https://segmentfault.com/a/1190000007849893
user-select属性是css3新增的属性,用于设置用户是否能够选中文本
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
23.# [vue中watch的用法 ]
this.$watch(`domainObject.goodsLoss`, (val) => {})
23.# vue-tool 浏览器工具与调试
一般情况下国内google 会被墙,所以,直接在 git 上下载下来,然后本地安装vue-tool
引用链接
http://blog.csdn.net/sinat_17775997/article/details/70224280
24.#watch 方法的使用
this.$watch(`domainObject.${this.configData.field}`, (val, oldval) => {
console.log('检测到select值变更', val, oldval);
// if (this.editable === false) {
this.refreshSelect();
// }
});
25.#img 图片url 判断图片的 width
// 判断图片大小
let self = this;
this.$watch(`dialogImageUrl`, (val, oldval) => {
console.log('检测到dialogImageUrl 改变 ...', val, oldval);
// this.refreshSelect();
let img = new Image();
let W = 0;
img.src = val;
if(img.complete){
// console.log('from:complete : width:'+img.width+',height:'+img.height);
self.imgType = img.width>780 ? 'full' : 'large';
}else{
img.onload = function(){
// console.log('from:onload : width:'+img.width+',height:'+img.height);
// W = img.width;
self.imgType = img.width>780 ? 'full' : 'large';
}
}
});