Vue:實戰快速上手

  咱們採用實戰教學模式並結合 ElementUI 組件庫,將所需知識點應用到實際中,以最快速度帶領你們掌握 Vue 的使用。javascript

建立工程

1. 建立名爲hello-vue 的工程css

  vue init webpack hello-vuevue

2. 安裝所須要的依賴java

進入工程目錄中node

npm install   //安裝基礎依賴webpack

npm install vue-router --save-dev   //安裝路由依賴ios

npm i element-ui -S   // 安裝elementUI依賴web

cnpm install sass-loader node-sass --save-dev   //安裝css擴展性語言依賴vue-router

# 啓動npm

npm run dev

三、Npm命令解釋:

  • npm install moduleName:安裝模塊到項目目錄下
  • npm install -g moduleName:-g 的意思是將模塊安裝到全局,具體安裝到磁盤哪一個位置,要看 npm config prefix 的位置
  • npm install -save moduleName:--save 的意思是將模塊安裝到項目目錄下,並在 package 文件的 dependencies 節點寫入依賴,-S 爲該命令的縮寫
  • npm install -save-dev moduleName:--save-dev 的意思是將模塊安裝到項目目錄下,並在 package 文件的 devDependencies 節點寫入依賴,-D 爲該命令的縮寫

建立登陸頁面

把沒有用的初始化東西刪掉!

在源碼目錄中建立以下結構:

建立首頁視圖,在 views 目錄下建立一個名爲 Main.vue 的視圖組件

 

建立登陸頁視圖在 views 目錄下建立一個名爲 Login.vue 的視圖組件,其中 el-* 的元素爲 ElementUI 組件;

<template>
  <div>
    <el-form ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box">
      <h3 class="login-title">歡迎登陸</h3>
      <el-form-item label="帳號" prop="username">
        <el-input type="text" placeholder="請輸入帳號" v-model="form.username"/>
      </el-form-item>
      <el-form-item label="密碼" prop="password">
        <el-input type="password" placeholder="請輸入密碼" v-model="form.password"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-on:click="onSubmit('loginForm')">登陸</el-button>
      </el-form-item>
    </el-form>

    <el-dialog
      title="舒適提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <span>請輸入帳號和密碼</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">確 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "Login",
    data() {
      return {
        form: {
          username: '',
          password: ''
        },

        // 表單驗證,須要在 el-form-item 元素中增長 prop 屬性
        rules: {
          username: [
            {required: true, message: '帳號不可爲空', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '密碼不可爲空', trigger: 'blur'}
          ]
        },

        // 對話框顯示和隱藏
        dialogVisible: false
      }
    },
    methods: {
      onSubmit(formName) {
        // 爲表單綁定驗證功能
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // 使用 vue-router 路由到指定頁面,該方式稱之爲編程式導航
            this.$router.push("/main");
          } else {
            this.dialogVisible = true;
            return false;
          }
        });
      }
    }
  }
</script>

<style lang="scss" scoped>
  .login-box {
    border: 1px solid #DCDFE6;
    width: 350px;
    margin: 180px auto;
    padding: 35px 35px 15px 35px;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    box-shadow: 0 0 25px #909399;
  }

  .login-title {
    text-align: center;
    margin: 0 auto 40px auto;
    color: #303133;
  }
</style>

建立路由,在 router 目錄下建立一個名爲 index.js 的 vue-router 路由配置文件

import Vue from 'vue'
import Router from 'vue-router'

import Login from "../views/Login"
import Main from '../views/Main'

Vue.use(Router);

export default new Router({
  routes: [
    {
      // 登陸頁
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      // 首頁
      path: '/main',
      name: 'Main',
      component: Main
    }
  ]
});

 配置路由,修改入口代碼,修改 main.js 入口代碼

import Vue from 'vue'
import VueRouter from 'vue-router'
import router from './router'

// 導入 ElementUI
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

import App from './App'

// 安裝路由
Vue.use(VueRouter);

// 安裝 ElementUI
Vue.use(ElementUI);

new Vue({
  el: '#app',
  // 啓用路由
  router,
  // 啓用 ElementUI
  render: h => h(App)
});

修改 App.vue 組件代碼

<template>
  <div id="app">
    <router-view/>
  </div>
</template>

<script>
  export default {
    name: 'App',
  }
</script>

測試 : 在瀏覽器打開 http://localhost:8080/#/login

若是出現錯誤: 多是由於sass-loader的版本太高致使的編譯錯誤,當前最高版本是8.x,須要退回到7.3.1 ;

去package.json文件裏面的 "sass-loader"的版本更換成7.3.1,而後從新cnpm install就能夠了;

 


路由嵌套

  嵌套路由又稱子路由,在實際應用中,一般由多層嵌套的組件組合而成。一樣地,URL 中各段動態路徑也按某種結構對應嵌套的各層組件,例如:

  

 

 

一、用戶信息組件,在 views/user 目錄下建立一個名爲 Profile.vue 的視圖組件;

 

 二、用戶列表組件在 views/user 目錄下建立一個名爲 List.vue 的視圖組件;

 

 三、配置嵌套路由修改 router 目錄下的 index.js 路由配置文件,代碼如

import Vue from 'vue'
import Router from 'vue-router'

import Login from "../views/Login"
import Main from '../views/Main'

// 用於嵌套的路由組件
import UserProfile from '../views/user/Profile'
import UserList from '../views/user/List'

Vue.use(Router);

export default new Router({
  routes: [
    {
      // 登陸頁
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      // 首頁
      path: '/main',
      name: 'Main',
      component: Main,
      // 配置嵌套路由
      children: [
        {path: '/user/profile', component: UserProfile},
        {path: '/user/list', component: UserList},
      ]
    }
  ]
});

 說明:主要在路由配置中增長了 children 數組配置,用於在該組件下設置嵌套路由

 四、修改首頁視圖,咱們修改 Main.vue 視圖組件,此處使用了 ElementUI 佈局容器組件,代碼以下:

<template>
    <div>
      <el-container>
        <el-aside width="200px">
          <el-menu :default-openeds="['1']">
            <el-submenu index="1">
              <template slot="title"><i class="el-icon-caret-right"></i>用戶管理</template>
              <el-menu-item-group>
                <el-menu-item index="1-1">
                  <router-link to="/user/profile">我的信息</router-link>
                </el-menu-item>
                <el-menu-item index="1-2">
                  <router-link to="/user/list">用戶列表</router-link>
                </el-menu-item>
              </el-menu-item-group>
            </el-submenu>
            <el-submenu index="2">
              <template slot="title"><i class="el-icon-caret-right"></i>內容管理</template>
              <el-menu-item-group>
                <el-menu-item index="2-1">分類管理</el-menu-item>
                <el-menu-item index="2-2">內容列表</el-menu-item>
              </el-menu-item-group>
            </el-submenu>
          </el-menu>
        </el-aside>

        <el-container>
          <el-header style="text-align: right; font-size: 12px">
            <el-dropdown>
              <i class="el-icon-setting" style="margin-right: 15px"></i>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>我的信息</el-dropdown-item>
                <el-dropdown-item>退出登陸</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-header>

          <el-main>
            <router-view />
          </el-main>
        </el-container>
      </el-container>
    </div>
</template>

<script>
    export default {
        name: "Main"
    }
</script>

<style scoped lang="scss">
  .el-header {
    background-color: #B3C0D1;
    color: #333;
    line-height: 60px;
  }

  .el-aside {
    color: #333;
  }
</style>

說明:

  在 <el-main> 元素中配置了 <router-view /> 用於展現嵌套路由,主要使用 <router-link to="/user/profile">我的信息</router-link> 展現嵌套路由內容

參數傳遞

  咱們常常須要把某種模式匹配到的全部路由,全都映射到同個組件。例如,咱們有一個 User 組件,對於全部 ID 各不相同的用戶,都要使用這個組件來渲染。此時咱們就須要傳遞參數了;

一、修改路由配置, 主要是在 path 屬性中增長了 :id 這樣的佔位符

{path: '/user/profile/:id', name:'UserProfile', component: UserProfile}

二、傳遞參數

  此時咱們將 to 改成了 :to,是爲了將這一屬性當成對象使用,注意 router-link 中的 name 屬性名稱 必定要和 路由中的 name 屬性名稱 匹配,由於這樣 Vue 才能找到對應的路由路徑;

<router-link :to="{name: 'UserProfile', params: {id: 1}}">我的信息</router-link>

三、接收參數, 在目標組件中

{{ $route.params.id }}

使用 props 的方式

一、修改路由配置 , 主要增長了 props: true 屬性

{path: '/user/profile/:id', name:'UserProfile', component: UserProfile, props: true}

二、傳遞參數和以前同樣
三、接收參數爲目標組件增長 props 屬性

組件重定向

重定向的意思你們都明白,但 Vue 中的重定向是做用在路徑不一樣但組件相同的狀況下,好比:

說明:這裏定義了兩個路徑,一個是 /main ,一個是 /goHome,其中 /goHome 重定向到了 /main 路徑,由此能夠看出重定向不須要定義組件;

使用的話,只須要設置對應路徑便可;

路由模式與 404

  路由模式有兩種

  

  修改路由配置,代碼以下:

  

  處理 404 建立一個名爲 NotFound.vue 的視圖組件,代碼以下:

   

  修改路由配置,代碼以下:

   

路由鉤子與異步請求

beforeRouteEnter:在進入路由前執行
beforeRouteLeave:在離開路由前執行

上代碼:

 

在鉤子函數中使用異步請求

一、安裝 Axios cnpm install axios -s
二、main.js引用 Axios

三、準備數據 : 只有咱們的 static 目錄下的文件是能夠被訪問到的,因此咱們就把靜態文件放入該目錄下。

四、在 beforeRouteEnter 中進行異步請求

 export default {
    props: ['id'],
    name: "UserProfile",
    beforeRouteEnter: (to, from, next) => {
      console.log("準備進入我的信息頁");
      // 注意,必定要在 next 中請求,由於該方法調用時 Vue 實例尚未建立,此時沒法獲取到 this 對象,在這裏使用官方提供的回調函數拿到當前實例
      next(vm => {
        vm.getData();
      });
    },
    beforeRouteLeave: (to, from, next) => {
      console.log("準備離開我的信息頁");
      next();
    },
    methods: {
      getData: function () {
        this.axios({
          method: 'get',
          url: 'http://localhost:8080/static/mock/data.json'
        }).then(function (repos) {
          console.log(repos);
        }).catch(function (error) {
          console.log(error);
        });
      }
    }
  }
相關文章
相關標籤/搜索