Vue 常用語法指南

下面都是總結的 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 個請求,兩個請求都返回才會 繼續下一步

  1. 發出兩個請求 同時發出,但是,需要都返回才能 做下一步操作
    解決辦法
    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';
              }
            }
        });
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

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