日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

vue----第一个工程项目

發布時間:2024/9/5 vue 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 vue----第一个工程项目 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1、創建工程

vue init webpack hello-vue

安裝依賴

# 進入工程目錄 cd hello-vue # 安裝 vue-router npm install vue-router --save-dev # 安裝 element-ui npm i element-ui -S # 安裝 SASS 加載器 npm install sass-loader node-sass --save-dev # 安裝依賴 npm install

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?為該命令的縮寫

啟動工程

npm run dev

  

  

第一個 ElementUI 頁面 (登錄頁)

主流框架

iView

iview 是一個強大的基于 Vue 的 UI 庫,有很多實用的基礎組件比 elementui 的組件更豐富,主要服務于 PC 界面的中后臺產品。使用單文件的 Vue 組件化開發模式 基于 npm + webpack + babel 開發,支持 ES2015 高質量、功能豐富 友好的 API ,自由靈活地使用空間。

  • 官網地址
  • Github
  • iview-admin

備注:屬于前端主流框架,選型時可考慮使用,主要特點是移動端支持較多

ElementUI

Element 是餓了么前端開源維護的 Vue UI 組件庫,組件齊全,基本涵蓋后臺所需的所有組件,文檔講解詳細,例子也很豐富。主要用于開發 PC 端的頁面,是一個質量比較高的 Vue UI 組件庫。

  • 官網地址
  • Github
  • vue-element-admin

備注:屬于前端主流框架,選型時可考慮使用,主要特點是桌面端支持較多

創建視圖

創建首頁視圖

在?views?目錄下創建一個名為?Main.vue?的視圖組件;該組件在當前章節無任何作用,主要用于登錄后展示登錄成功的跳轉效果;

<template><div>首頁</div> </template><script>export default {name: "Main"} </script><style scoped></style>

創建登錄頁視圖

在?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-dialogtitle="溫馨提示":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,// 啟用 ElementUIrender: h => h(App) });

修改?App.vue?組件代碼

<template><div id="app"><router-view/></div> </template><script>export default {name: 'App',} </script>

  

2、配置嵌套路由

什么是嵌套路由

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

創建嵌套視圖組件

用戶信息組件

在?views/user?目錄下創建一個名為?Profile.vue?的視圖組件;該組件在當前章節無任何作用,主要用于展示嵌套效果;

<template><div>個人信息</div> </template><script>export default {name: "UserProfile"} </script><style scoped></style>

用戶列表組件

在?views/user?目錄下創建一個名為?List.vue?的視圖組件;該組件在當前章節無任何作用,主要用于展示嵌套效果;

<template><div>用戶列表</div> </template><script>export default {name: "UserList"} </script><style scoped></style>

  

配置嵌套路由

修改?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><span>Lusifer</span></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>?展示嵌套路由內容

3、參數傳遞

概述

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

使用路徑匹配的方式

修改路由配置

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

  說明:主要是在?path?屬性中增加了?:id?這樣的占位符

傳遞參數

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

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

代碼方式

this.$router.push({ name: 'UserProfile', params: {id: 1}});  

接收參數

在目標組件中使用

{{ $route.params.id }}  

使用?props?的方式

修改路由配置

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

  說明:主要增加了?props: true?屬性

傳遞參數

同上

接收參數

為目標組件增加?props?屬性,代碼如下:

export default {props: ['id'],name: "UserProfile"}

模板中使用

{{ id }}

  

4、組件重定向

配置重定向

修改路由配置

{path: '/main',name: 'Main',component: Main }, {path: '/goHome',redirect: '/main' }

  說明:這里定義了兩個路徑,一個是?/main?,一個是?/goHome,其中?/goHome?重定向到了?/main?路徑,由此可以看出重定向不需要定義組件;

重定向到組件

設置對應路徑即可

<router-link to="/goHome">回到首頁</router-link>

  

帶參數的重定向

修改路由配置

{// 首頁path: '/main/:username',name: 'Main',component: Main},{path: '/goHome/:username',redirect: '/main/:username' }  

重定向到組件

<router-link to="/goHome/Lusifer">回到首頁</router-link>

  

5、路由模式與 404

路由模式

路由模式有兩種

  • hash:路徑帶?#?符號,如?http://localhost/#/login
  • history:路徑不帶?#?符號,如?http://localhost/login

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

export default new Router({mode: 'history',routes: [] });

處理 404

創建一個名為?NotFound.vue?的視圖組件,代碼如下:

<template><div>頁面不存在,請重試!</div> </template><script>export default {name: "NotFount"} </script><style scoped></style>

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

{path: '*',component: NotFound}

  

6、路由鉤子與異步請求

?

路由中的鉤子函數

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

案例代碼如下:

export default {props: ['id'],name: "UserProfile",beforeRouteEnter: (to, from, next) => {console.log("準備進入個人信息頁");next();},beforeRouteLeave: (to, from, next) => {console.log("準備離開個人信息頁");next();}}

參數說明:

  • to:路由將要跳轉的路徑信息
  • from:路徑跳轉前的路徑信息
  • next:路由的控制參數
    • next()?跳入下一個頁面
    • next('/path')?改變路由的跳轉方向,使其跳到另一個路由
    • next(false)?返回原來的頁面
    • next((vm)=>{})?僅在 beforeRouteEnter 中可用,vm 是組件實例

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

安裝 Axios

npm install axios -s

引用 Axios(修改main.js)

import axios from 'axios' Vue.prototype.axios = axios;

在?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/data.json'}).then(function (repos) {console.log(repos);}).catch(function (error) {console.log(error);});}}}

  

Vuex 快速入門

簡介

Vuex 是一個專為 Vue.js 應用程序開發的?狀態管理模式。它采用集中式存儲管理應用的所有組件的狀態,并以相應的規則保證狀態以一種可預測的方式發生變化。

目標

繼續之前?vue-router?章節做的案例項目,我們通過完善登錄功能將用戶信息保存至 Vuex 中來體會它的作用;

安裝

在項目根目錄執行如下命令來安裝 Vuex

判斷用戶是否登錄

我們利用路由鉤子?beforeEach?來判斷用戶是否登錄,期間會用到?sessionStorage?存儲功能

修改?Login.vue

在表單驗證成功方法內增加如下代碼:

// 設置用戶登錄成功 sessionStorage.setItem('isLogin', 'true');

修改?main.js

利用路由鉤子?beforeEach?方法判斷用戶是否成功登錄,關鍵代碼如下:

// 在跳轉前執行 router.beforeEach((to, form, next) => {// 獲取用戶登錄狀態let isLogin = sessionStorage.getItem('isLogin');// 注銷if (to.path == '/logout') {// 清空sessionStorage.clear();// 跳轉到登錄next({path: '/login'});}// 如果請求的是登錄頁else if (to.path == '/login') {if (isLogin != null) {// 跳轉到首頁next({path: '/main'});}}// 如果為非登錄狀態else if (isLogin == null) {// 跳轉到登錄頁next({path: '/login'});}// 下一個路由next(); });

配置?vuex

創建 Vuex 配置文件

在?src?目錄下創建一個名為?store?的目錄并新建一個名為?index.js?文件用來配置 Vuex,代碼如下:

import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex);// 全局 state 對象,用于保存所有組件的公共數據 const state = {// 定義一個 user 對象// 在組件中是通過 this.$store.state.user 來獲取user: {username: ''} };// 實時監聽 state 值的最新狀態,注意這里的 getters 可以理解為計算屬性 const getters = {// 在組件中是通過 this.$store.getters.getUser 來獲取,頁面上使用{{$store.getters.getUser.username}}來獲取getUser(state) {return state.user;} };// 定義改變 state 初始值的方法,這里是唯一可以改變 state 的地方,缺點是只能同步執行 const mutations = {// 在組件中是通過 this.$store.commit('updateUser', user); 方法來調用 mutationsupdateUser(state, user) {state.user = user;} };// 定義觸發 mutations 里函數的方法,可以異步執行 mutations 里的函數 const actions = {// 在組件中是通過 this.$store.dispatch('asyncUpdateUser', user); 來調用 actionsasyncUpdateUser(context, user) {context.commit('updateUser', user);} };export default new Vuex.Store({state,getters,mutations,actions });

修改?main.js?增加剛才配置的?store/index.js,關鍵代碼如下:

import Vue from 'vue' import Vuex from 'vuex' import store from './store'Vue.use(Vuex);new Vue({el: '#app',store });

解決瀏覽器刷新后 Vuex 數據消失問題

問題描述

Vuex 的狀態存儲是響應式的,當 Vue 組件從 store 中讀取狀態的時候,若 store 中的狀態發生變化,那么相應的組件也會相應地得到高效更新。但是有一個問題就是:vuex 的存儲的數據只是在頁面的中,相當于我們定義的全局變量,刷新之后,里邊的數據就會恢復到初始化狀態。但是這個情況有時候并不是我們所希望的。

解決方案

監聽頁面是否刷新,如果頁面刷新了,將 state 對象存入到 sessionStorage 中。頁面打開之后,判斷 sessionStorage 中是否存在 state 對象,如果存在,則說明頁面是被刷新過的,將 sessionStorage 中存的數據取出來給 vuex 中的 state 賦值。如果不存在,說明是第一次打開,則取 vuex 中定義的 state 初始值。

修改代碼

在?App.vue?中增加監聽刷新事件

export default {name: 'App',mounted() {window.addEventListener('unload', this.saveState);},methods: {saveState() {sessionStorage.setItem('state', JSON.stringify(this.$store.state));}}}

修改?store/index.js?中的 state

const state = sessionStorage.getItem('state') ? JSON.parse(sessionStorage.getItem('state')) : {user: {username: ''} }; 

模塊化

由于使用單一狀態樹,應用的所有狀態會集中到一個比較大的對象。當應用變得非常復雜時,store 對象就有可能變得相當臃腫。為了解決以上問題,Vuex 允許我們將 store 分割成模塊(module)。每個模塊擁有自己的 state、mutation、action、getter、甚至是嵌套子模塊——從上至下進行同樣方式的分割

創建?user?模塊

在?store?目錄下創建一個名為?modules?的目錄并創建一個名為?user.js?的文件,代碼如下:

const user = {// 因為模塊化了,所以解決刷新問題的代碼需要改造一下state: sessionStorage.getItem('userState') ? JSON.parse(sessionStorage.getItem('userState')) : {user: {username: ''}},getters: {getUser(state) {return state.user;}},mutations: {updateUser(state, user) {state.user = user;}},actions: {asyncUpdateUser(context, user) {context.commit('updateUser', user);}} };export default user;

修改?store/index.js

import Vue from 'vue' import Vuex from 'vuex'import user from './modules/user'Vue.use(Vuex);export default new Vuex.Store({modules: {// this.$store.state.useruser} });

備注:由于組件中使用的是?getters?和?actions?處理,所以調用代碼不變

修改?App.vue

export default {name: 'App',mounted() {window.addEventListener('unload', this.saveState);},methods: {saveState() {// 模塊化后,調用 state 的代碼修改為 this.$store.state.user(需要定位到user這個對象)sessionStorage.setItem('userState', JSON.stringify(this.$store.state.user));}}}

  

?

轉載于:https://www.cnblogs.com/yanxiaoge/p/11104586.html

總結

以上是生活随笔為你收集整理的vue----第一个工程项目的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。