vue 2的使用心得


title: vue 2的使用心得
date: 2017-05-25 18:13:01
tags: ['vue 表單驗(yàn)證','vue跳轉(zhuǎn)頁面','vue攔截器']


elementUI 網(wǎng)站快速成型工具

elementUI官網(wǎng) vue官網(wǎng) vue-router官網(wǎng)

頁面之間的路由配置及傳參

// home.vue中寫入
<template>
    <div>
        <router-link to="/nav">跳轉(zhuǎn)頁面</router-link>
        <el-button type="primary" @click="goHeader">主要按鈕</el-button>
        <router-link :to="{ name: 'header', params: { userId: 123 }}">header頁面?zhèn)鲄?lt;/router-link>
    </div>
</template>
<script>
    export default{
        name: 'home',
        data(){
            return {}
        },
        methods: {
            goHeader: function () {
                // 字符串
                this.$router.push('header/123')
                // 對象
                this.$router.push({path: 'header/0'})
                // 命名的路由
                this.$router.push({name: 'header', params: {userId: 1}})
            }
        }
    }
</script>

<style>
</style>

// 在router.js文件中寫入
// 引用模板
import header from '../components/header.vue'
import home from '../components/home.vue'
import nav from '../components/frame/nav.vue'
// 配置路由
export default [
    {
        path: '/',
        component: home
    },
    {
        path: '/nav',
        component: nav
    },
    {
        path: '/header/:userId',
        name: 'header',
        component: header
    }
]

// 接收參數(shù)  this.$route.params.userId
vue如何使用組件
<template>
    <div>
        <steps></steps>   
    </div>
</template>
<script>
// 第一種方法
    import Steps from './steps.vue'  //此處引入
    export default{
        components: {Steps},   // 此處注冊組件闰集,調(diào)用的時(shí)候硕旗,要用大寫
        name: 'home',
        data(){
            return {
                dialogFormVisible: false,
            }
        },
    }
// 第二種方法
    var Steps = require('./steps.vue'); // 返回的是一個(gè)組件腮恩,必須注冊才能使用
    export default{
        components: {'steps': Steps},
        //components: {'steps': require('./steps.vue')},  // 換了一種表達(dá)式
        name: 'home',
        data(){
            return {
                dialogFormVisible: false,
            }
        },
    }
</script>

<style scope>
</style>
vue2.0之a(chǎn)xios使用
發(fā)送一個(gè)get請求:
axios.get('/user', {
params: {
ID: 12345
}}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
第一種方法:
 var params = {
     loginCode: this.loginCode,
     passWord: this.passWord,
     url: 'yatouLogin'
 }
 // 發(fā)送post請求把對象轉(zhuǎn)成字符串
 var postparams = new URLSearchParams();
 postparams.append('loginCode', this.loginCode);
 postparams.append('passWord', this.passWord);
 this.$http.post('yatouLogin', postparams).then(function (res) {
     console.log(res);
     if (res.data.success) {
         that.$router.push({path: 'nav'})
         localStorage.clear('powerList');
         localStorage.setItem('powerList', JSON.stringify(res.data.data))
     } else {
         that.$message.error(res.data.errMsg);
     }
 }).catch(function (response) {
     console.log(response);
});

第二種方法:
在main.js中配置axiso的屬性
import axios from 'axios'
import qs from 'qs'

Vue.use(qs);
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';           //配置請求頭
axios.defaults.baseURL = 'http://wx.bokedata.com/yatou/';
//設(shè)置攜帶session完域,解決跨域
axios.defaults.withCredentials = true;
Vue.prototype.$http = axios;
const router = new VueRouter({
  routes
})
// 攔截器處理post的參數(shù)
axios.interceptors.request.use((config) => {
    if(config.method  === 'post'){
        config.data = qs.stringify(config.data);
    }
    return config;
},(error) =>{
     _.toast("錯(cuò)誤的傳參", 'fail');
    return Promise.reject(error);
})
// 調(diào)用接口
var params = {
    loginCode: this.loginCode,
    passWord: this.passWord,
    url: 'yatouLogin'
}
this.$http.post(params.url, {
    'loginCode': params.loginCode,
    'passWord': params.passWord
}).then(function (res) {
    console.log(res);
    if (res.data.success) {
        that.$router.push({path: 'nav'})
        localStorage.clear('powerList');
        localStorage.setItem('powerList', JSON.stringify(res.data.data))
    } else {
        that.$message.error(res.data.errMsg);
    }
})


調(diào)用組件及傳值問題
向main.js中引入組件
import componnets from './components/common/component.vue'
Vue.component('component', componnets)
<el-button type="primary" @click="componentProp()">主要按鈕</el-button>
<!--組件調(diào)用 :xx 為設(shè)置變量-->
<component :is="dialogTest" :id="id" v-if="destroyDialog"></component>
methods: {
     // 向父頁面?zhèn)鬟^來的值
     componentProp(){
         this.destroyDialog=true;
         this.id = '001'
         this.dialogTest = 'component'
         this.destroyDialog=true;
     },
 }

組件的模版頁面

<template>
    <div class="component">
        <el-dialog title="收貨地址" :visible.sync="dialogFormVisible">
            <el-form :model="form">
                <el-form-item label="活動(dòng)名稱">
                    <el-input v-model="form.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="活動(dòng)區(qū)域">
                    <el-select v-model="form.region" placeholder="請選擇活動(dòng)區(qū)域">
                        <el-option label="區(qū)域一" value="shanghai"></el-option>
                        <el-option label="區(qū)域二" value="beijing"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false;cancal()">取 消</el-button>
                <el-button type="primary" @click="dialogFormVisible = false">確 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>
<script>
    export default {
        data() {
            return {
                dialogFormVisible: false,
                form: {
                    name: '',
                    region: '',
                    date1: '',
                    date2: '',
                    delivery: false,
                    type: [],
                    resource: '',
                    desc: ''
                }
            };
        },
        // 父頁面?zhèn)鬟^來的值
        props: ['id'],
        methods: {
            cancal(){
                // 父元素為關(guān)閉
                this.$parent.destroyDialog = false;
            }
        },
        mounted: function () {
            var that = this;
            console.log(this.id);
            this.dialogFormVisible = true

        }
    };

</script>
<style>
</style>
表單驗(yàn)證
 <el-form :model="edit" :rules="rules">
            <el-form-item label="編碼" prop="code">
                <el-input v-model="edit.code"></el-input>
            </el-form-item>
            <el-form-item label="電話號(hào)碼" prop="telephone">
                <el-input v-model="edit.telephone"></el-input>
            </el-form-item>
            <el-form-item label="備注" prop="remark">
                <el-input v-model="edit.name"></el-input>
            </el-form-item>
</el-form>
  data(){
       return {
            edit: {},
            rules: {
                //編碼輸入框驗(yàn)證規(guī)則
                code: [
                    {required: true, message: '編碼不能為空', trigger: 'blur'}
                ],
                //名稱輸入框驗(yàn)證規(guī)則
                name: [
                    {required: true, message: '名稱不能為空', trigger: 'blur'}
                ],
                //備注輸入框驗(yàn)證規(guī)則
                telephone: [
                    {required: true, message: '電話不能為空', trigger: 'blur'},
                    {
                        validator(r, v, b){
                            (/^\d{2,}$/).test(v) ? b() : b(new Error('請?zhí)顚懯謾C(jī)號(hào)'))
                        }
                    }
                ]
            }
        }
  

攔截器的使用
axios.interceptors.response.use(function (response) {
    // 處理響應(yīng)數(shù)據(jù)
    if (response.data.respCode == '000001') {
        // ElementUI.Message.error('服務(wù)器異常')
        ElementUI.MessageBox('此登錄信息已過期换薄,請重新登錄', '提示', {
            confirmButtonText: '確定',
            type: 'warning'
        }).then(() => {
            router.replace({
                path: '/',
            })
        });
    }
    return response;
}, function (error) {
    // 處理響應(yīng)失敗
    if (error.response.status == 500) {
        ElementUI.Message.error('服務(wù)器異常')
    } else if (error.response.status == 404) {
        ElementUI.Message.error('資源不存在')
    } else if (error.response.status == 405) {
        ElementUI.Message.error('請求方法錯(cuò)誤')
    }
});

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市副签,隨后出現(xiàn)的幾起案子论衍,更是在濱河造成了極大的恐慌,老刑警劉巖楣责,帶你破解...
    沈念sama閱讀 218,284評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件竣灌,死亡現(xiàn)場離奇詭異,居然都是意外死亡秆麸,警方通過查閱死者的電腦和手機(jī)初嘹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來沮趣,“玉大人屯烦,你說我怎么就攤上這事》棵” “怎么了驻龟?”我有些...
    開封第一講書人閱讀 164,614評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長育叁。 經(jīng)常有香客問我迅脐,道長,這世上最難降的妖魔是什么豪嗽? 我笑而不...
    開封第一講書人閱讀 58,671評(píng)論 1 293
  • 正文 為了忘掉前任谴蔑,我火速辦了婚禮,結(jié)果婚禮上龟梦,老公的妹妹穿的比我還像新娘隐锭。我一直安慰自己,他們只是感情好计贰,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,699評(píng)論 6 392
  • 文/花漫 我一把揭開白布钦睡。 她就那樣靜靜地躺著,像睡著了一般躁倒。 火紅的嫁衣襯著肌膚如雪荞怒。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,562評(píng)論 1 305
  • 那天秧秉,我揣著相機(jī)與錄音褐桌,去河邊找鬼。 笑死象迎,一個(gè)胖子當(dāng)著我的面吹牛荧嵌,可吹牛的內(nèi)容都是我干的呛踊。 我是一名探鬼主播,決...
    沈念sama閱讀 40,309評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼啦撮,長吁一口氣:“原來是場噩夢啊……” “哼谭网!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起赃春,我...
    開封第一講書人閱讀 39,223評(píng)論 0 276
  • 序言:老撾萬榮一對情侶失蹤愉择,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后织中,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體薄辅,經(jīng)...
    沈念sama閱讀 45,668評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,859評(píng)論 3 336
  • 正文 我和宋清朗相戀三年抠璃,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了站楚。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,981評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡搏嗡,死狀恐怖窿春,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情采盒,我是刑警寧澤旧乞,帶...
    沈念sama閱讀 35,705評(píng)論 5 347
  • 正文 年R本政府宣布,位于F島的核電站磅氨,受9級(jí)特大地震影響尺栖,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜烦租,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,310評(píng)論 3 330
  • 文/蒙蒙 一延赌、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧叉橱,春花似錦挫以、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至粪小,卻和暖如春大磺,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背探膊。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評(píng)論 1 270
  • 我被黑心中介騙來泰國打工杠愧, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人突想。 一個(gè)月前我還...
    沈念sama閱讀 48,146評(píng)論 3 370
  • 正文 我出身青樓殴蹄,卻偏偏與公主長得像,于是被迫代替她去往敵國和親猾担。 傳聞我的和親對象是個(gè)殘疾皇子袭灯,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,933評(píng)論 2 355

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