Vue 常用語法指南

下面都是總結(jié)的 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.獲取路由的參數(shù)
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.路由跳轉(zhuǎn)
 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處需要導(dǎo)入

最簡單的如下
var eventMain;
// http://blog.csdn.net/magic__man/article/details/51831227
//添加監(jiān)聽  name funEvent 執(zhí)行的函數(shù)
function addEvent(name, funEvent) {
    //  document.addEventListener('oneating', function (event) {  
    //      alert(event.mingzi+'赞哗,'+event.message);  
    //  }, false);  
    document.addEventListener(name,funEvent(event), false);
}
//發(fā)出事件 name 事件的名字 objc 事件傳遞的參數(shù)种蝶,為objc
function sendEvent(name, objc) {
    var event = document.createEvent('HTMLEvents');
    event.initEvent(name, true, true);
    event.canshu = objc;
    document.dispatchEvent(event);
}
var vmEvent ;
發(fā)送消息
<template>
    <div class="list">
        list one
        <div @click='event()'>
            傳遞參數(shù) 88 請點擊
        </div>
    </div>
</template>

methods: {
            event: function(e) {
                sendEvent('list', 'message:傳遞信息趟佃,位置:listTwo');
            }
        }
接收消息客税,直接在生命周期的方法里面寫 即可
mounted: function() {
            catchEvent('list',function(event){
                alert('接收到消息了惨恭,此處位于listTwo'+event.info);
            })
        }

10.Vue 簡單傳值 父子之間

在子組件里面加監(jiān)聽方法系草,一般都是 點擊方法通熄,因為方便eventEmit
<template>
    <div class="list">
        list one
        <div @click='event()'>
            傳遞參數(shù) 88 請點擊
        </div>
        <div @click='eventEmit()'>
            點擊我 通過 emit 方法傳遞參數(shù)給 list(父組件)
        </div>
    </div>
</template>

    methods: {
            eventEmit: function() {
                //注意此處的 eventEmit 不能錯,參數(shù)也可傳過去
                this.$emit('eventEmit','message:這句話是通過$emit 傳值過去的位置listOne');
            }
        },
在父組件中 通過v-on 綁定過去
<template>
    <div class="list">
        list 本頁id
        <h2>User {{ $route.params.id }}</h2>
        <div @click='event(88)'>
            傳遞參數(shù)
        </div>
        <ListOne v-on:eventEmit="eventEmitList"></ListOne>
        <ListTwo></ListTwo>
    </div>
</template>

methods: {
            eventEmitList: function(msg) {
                alert('通過emit 收到的消息list 參數(shù)為:'+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('-');
}
//直接調(diào)用
import * as filters from './filters';
// register filters
Object.keys(filters).forEach(function(k) {
  Vue.filter(k, filters[k]);
});
12.Vue 中動態(tài)綁定數(shù)據(jù)
    // 生命周期方法 
        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 全局方法的設(shè)置

tool.js

import Vue from 'vue'

export default{
  install(Vue,options)
  {
    Vue.prototype.getData = function (val) {

      return val + '我是插件中的方法';
      // console.log('我是插件中的方法');
    }
// 全局變量  唇辨,直接 this. 即可調(diào)用
    Vue.prototype._name_my = 'fang chun gao ';
// 全局 filter 直接 {{stage |filtersrrr("uuu")}} 可以調(diào)用
    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 '哈哈赏枚,我是全局方法返回的數(shù)據(jù)';
};

使用的地方 (不用寫 this,區(qū)別在此)晓猛,方法需要每一個導(dǎo)出

import { toolsMethod }  from '../tool';
            var str = 'yyyyy';
                console.log(str);
                str =   toolsMethod(str);
                console.log(str); 

            },

14.Vue Element 中面包屑 動態(tài)跳轉(zhuǎn)
    <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 父組件 拿到子組件的值饿幅,并且 方法中帶入 父組件自己的參數(shù)
<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 中 網(wǎng)路請求

1.發(fā)出2 個請求,兩個請求都返回才會 繼續(xù)下一步

  1. 發(fā)出兩個請求 同時發(fā)出戒职,但是栗恩,需要都返回才能 做下一步操作
    解決辦法
    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 執(zhí)行完了 便順序執(zhí)行,(沒有返回 res 洪燥,上一步返回 err 此處依舊執(zhí)行)
          if(res.abc == 123){
              // 下一個網(wǎng)絡(luò)請求
          }
        })

Promise 的 all 方法

// 生成一個Promise對象的數(shù)組
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>

全局方法

   // 將 備注中 的 回車 符號全部 轉(zhuǎn)成 <br/>
      Vue.prototype.sortTipsToHtmlGol = function (tipString) {
        var res = '';
        res =   tipString.replace(/\n/g, "<br/>")
        return res;
      }
19.router(在當(dāng)前頁面 改變 地址欄中的參數(shù),并且刷新)

//當(dāng)前頁面的路由就是 /system/serviceAdd/1捧韵,需要將 1變成 10市咆,或則 增加 produceId 參數(shù)(場景)
// this.$router.go(0);刷新當(dāng)前頁面,相當(dāng)于 按了 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};

結(jié)果:


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
//設(shè)置值
this.$store.dispatch('sendHasRoot',true);
//取值
 computed:{
     ...mapGetters(["stepName","currentProject","userId","currentUser","hasJumpInApply","yearChange","changeProjectStatus"]),

項目中用法與結(jié)構(gòu)


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 中數(shù)組與 對象的復(fù)制 方法(淺拷貝)
http://blog.csdn.net/zgrkaka/article/details/70792297
數(shù)組
     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新增的屬性蒙兰,用于設(shè)置用戶是否能夠選中文本
  -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 瀏覽器工具與調(diào)試

一般情況下國內(nèi)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';
              }
            }
        });
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末膀斋,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子痹雅,更是在濱河造成了極大的恐慌仰担,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,000評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件绩社,死亡現(xiàn)場離奇詭異摔蓝,居然都是意外死亡,警方通過查閱死者的電腦和手機愉耙,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,745評論 3 399
  • 文/潘曉璐 我一進店門贮尉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人朴沿,你說我怎么就攤上這事猜谚。” “怎么了赌渣?”我有些...
    開封第一講書人閱讀 168,561評論 0 360
  • 文/不壞的土叔 我叫張陵魏铅,是天一觀的道長。 經(jīng)常有香客問我坚芜,道長览芳,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,782評論 1 298
  • 正文 為了忘掉前任鸿竖,我火速辦了婚禮沧竟,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘缚忧。我一直安慰自己悟泵,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 68,798評論 6 397
  • 文/花漫 我一把揭開白布搔谴。 她就那樣靜靜地躺著魁袜,像睡著了一般桩撮。 火紅的嫁衣襯著肌膚如雪敦第。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,394評論 1 310
  • 那天店量,我揣著相機與錄音芜果,去河邊找鬼。 笑死融师,一個胖子當(dāng)著我的面吹牛右钾,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 40,952評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼舀射,長吁一口氣:“原來是場噩夢啊……” “哼窘茁!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起脆烟,我...
    開封第一講書人閱讀 39,852評論 0 276
  • 序言:老撾萬榮一對情侶失蹤山林,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后邢羔,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體驼抹,經(jīng)...
    沈念sama閱讀 46,409評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,483評論 3 341
  • 正文 我和宋清朗相戀三年拜鹤,在試婚紗的時候發(fā)現(xiàn)自己被綠了框冀。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,615評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡敏簿,死狀恐怖明也,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情惯裕,我是刑警寧澤诡右,帶...
    沈念sama閱讀 36,303評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站轻猖,受9級特大地震影響帆吻,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜咙边,卻給世界環(huán)境...
    茶點故事閱讀 41,979評論 3 334
  • 文/蒙蒙 一猜煮、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧败许,春花似錦王带、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,470評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至醋寝,卻和暖如春搞挣,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背音羞。 一陣腳步聲響...
    開封第一講書人閱讀 33,571評論 1 272
  • 我被黑心中介騙來泰國打工囱桨, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人嗅绰。 一個月前我還...
    沈念sama閱讀 49,041評論 3 377
  • 正文 我出身青樓舍肠,卻偏偏與公主長得像搀继,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子翠语,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,630評論 2 359

推薦閱讀更多精彩內(nèi)容

  • Vue 實例 屬性和方法 每個 Vue 實例都會代理其 data 對象里所有的屬性:var data = { a:...
    云之外閱讀 2,221評論 0 6
  • 等一個人的下班 往往是在刷手機 抬頭看見一雙雙眼睛 逗趣的向你笑 ———————— 這是【每天的話】 每天只分享這...
    ShawnLim閱讀 175評論 0 0
  • 我在手機里休眠 一不小心跌在日歷里 我驚訝于這個日期 于是被你的生辰喊醒 這排阿拉伯?dāng)?shù)字 具有象征意義 一個肉胎 ...
    安瑞奧閱讀 471評論 0 0
  • 人們的左腦在處理數(shù)字運算時叽躯,尤其是相對復(fù)雜的數(shù)學(xué)計算,往往會耗時較長肌括,無法做出靈敏反應(yīng)险毁。 然而在密集錯雜的行人區(qū),...
    威威專欄閱讀 1,067評論 0 1
  • 別誤會,我還沒那么大慧库,離我22周歲的生日跷跪,還有不多不少,十個月而已啦吵瞻。 (嘻嘻,不知道這個時候投稿甘磨,編劇們會不會要...
    yiyi同學(xué)閱讀 961評論 3 1