vue入門筆記


VUE入門

頁面基礎組件參考文檔;(3條消息) 一篇文章,Vue快速入門!!!_cV展示的學習園-CSDN博客

Axios異步通信

Axios簡介

Axios是一個開源的可以用在瀏覽器端和Node JS的異步通信框架, 她的主要作用就是實現AJAX異步通信,其功能特點如下:

  • 從瀏覽器中創建XMLHttpRequests
  • 從node.js創建http請求
  • 支持Promise API[JS中鏈式編程]
  • 攔截請求和響應
  • 轉換請求數據和響應數據
  • 取消請求
  • 自動轉換JSON數據
  • 客戶端支持防御XSRF(跨站請求偽造)

由於Vue.js是一個視圖層框架並且作者(尤雨溪) 嚴格准守SoC(關注度分離原則)所以Vue.js並不包含AJAX的通信功能, 為了解決通信問題, 作者單獨開發了一個名為vue-resource的插件, 不過在進入2.0版本以后停止了對該插件的維護並推薦了Axios框架。

由於jQuery操作Dom太頻繁,所以少用

測試Axios

  • 准備數據
{
  "name": "cv戰士",
  "url": "https://blog.csdn.net/qq_45408390?spm=1001.2101.3001.5343",
  "page": 1,
  "isNonProfit": true,
  "address": {
    "street": "含光門",
    "city": "陝西西安",
    "country": "中國"
  },
  "links": [
    {
      "name": "bilibili",
      "url": "https://bilibili.com"
    },
    {
      "name": "cv戰士",
      "url": "https://blog.csdn.net/qq_45408390?spm=1001.2101.3001.5343"
    },
    {
      "name": "百度",
      "url": "https://www.baidu.com/"
    }
  ]
}
  • 測試代碼
<!DOCTYPE html>
<html lang="en" xmlns:v-binf="http://www.w3.org/1999/xhtml" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--v-cloak 解決閃爍問題-->
    <style>
        [v-cloak]{
            display: none;
        }
    </style>
</head>
<body>
<div id="vue" v-cloak>
    <div>地名:{{info.name}}</div>
    <div>地址:{{info.address.country}}--{{info.address.city}}--{{info.address.street}}</div>
    <div>鏈接:<a v-bind:href="info.url">{{info.url}}</a> </div>
</div>

<!--引入js文件-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
    var vm = new Vue({
        el:"#vue",
        //data:屬性:vm
        data(){
            return{
                info:{
                    name:null,
                    address:{
                        country:null,
                        city:null,
                        street:null
                    },
                    url:null
                }
            }
        },
        mounted(){//鈎子函數
            axios
                .get('../data.json')
                .then(response=>(this.info=response.data));
        }
    });
</script>
</body>
</html>

計算屬性、內容分發

自定義事件

<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--view層,模板-->
<div id="vue">
    <todo>
        <todo-title slot="todo-title" v-bind:title="title"></todo-title>
        <todo-items slot="todo-items" v-for="(item,index) in todoItems"
                    :item="item" :index="index" v-on:remove="removeItems(index)"></todo-items>
    </todo>
</div>
<!--1.導入Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<script type="text/javascript">
    Vue.component('todo',{
        template:'<div>\
                <slot name="todo-title"></slot>\
                <ul>\
                    <slot name="todo-items"></slot>\
                </ul>\
            </div>'
    });
    Vue.component('todo-title',{
        props:['title'],
        template:'<div>{{title}}</div>'
    });
    //這里的index,就是數組的下標,使用for循環遍歷的時候,可以循環出來!
    Vue.component("todo-items",{
        props:["item","index"],
        template:"<li>{{item}}---{{index}}<button @click='remove'>刪除</button></li>",
        methods: {
            remove: function (index) {
                this.$emit('remove',index);
            }
        }
    });
    var vm = new Vue({
        el:"#vue",
        data:{
            title:"cvzhanshi study java",
            todoItems:['test1','test2','test3']
        },
        methods: {
            removeItems: function (index) {
                this.todoItems.splice(index,1);
            }
        }
    });
</script>
</body>
</html>

通過上訴代碼我們可以發現一個問題,如果刪除操作要在組件中完成,那么組件如何刪除Vue實例中的數據?

例:[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-6cl2ga6d-1624517862625)(Vue.assets/1624501228359.png)]

刪除按鈕是在組件中的,點擊刪除按鈕刪除對應的數據。

閱讀Vue教程可知,此時就涉及到參數傳遞與事件分發了, Vue為我們提供了自定義事件的功能很好的幫助我們解決了這個問題; 組件中使用this.$emit(‘自定義事件名’, 參數) ,而在視圖層通過自定義事件綁定Vue中的刪除操作的方法

splice()方法是修改array的“萬能方法”,他可以從指定的索引開始刪除若干個元素,然后再從改位置添加若干個元素:

var arr = [ 'microsoft ', 'Apple ', 'Yahoo ', 'AOL', 'Excite ', 'oracle'];
//從索引2開始刪除3個元素,然后再添加兩個元素:
arr.splice(2,3,'6oogle ', 'Facebook ' );//返回刪除的元素['Yahoo', 'AoL ', 'Excite']
arr; //[ 'Microsoft ', 'Apple ', 'Google', 'Facebook ', 'oracle ' ]
//只刪除,不添加:
arr.splice( 2,2);  //[ 'Google ', 'Facebook ' ]
arr; //[ 'Microsoft ', ' Apple ', 'oracle ']
//只添加,不刪除:
arr.splice(2,0,y'6oogle ', 'Facebook ' );//返回[],因為沒有刪除任何元素
arr; // [ 'Microsbft ', 'Apple ' , 'Google ', 'Facebook ', 'oracle ' ]
image-20211114150750509

Vue入門小結

核心:數據驅動,組件化

優點:借鑒了AngularJS的模塊化開發和React的虛擬Dom,虛擬Dom就是把Demo操作放到內存中執行;

常用的屬性:

  • v-if
  • v-else-if
  • v-else
  • v-for
  • v-on綁定事件,簡寫@
  • v-model數據雙向綁定
  • v-bind給組件綁定參數,簡寫:

組件化

  • 組合組件slot插槽
  • 組件內部綁定事件需要使用到this.$emit(“事件名”,參數);
  • 計算屬性的特色,緩存計算數據

遵循SoC關注度分離原則,Vue是純粹的視圖框架,並不包含,比如Ajax之類的通信功能,為了解決通信問

題,我們需要使用Axios框架做異步通信;

node.js(環境)

  • 檢查node.js環境
C:\Users\XXXX>node -v
v16.11.1

C:\Users\XXXX>npm -v
8.0.0

  • 淘寶鏡像加速
# -g 就是全局安裝
npm install cnpm -g

# 或使用如下語句解決npm速度慢的問題,但是每次install都需要(媽發)
npm install --registry=https://registry.npm.taobao.org

盡量不用淘寶的可能會打包失敗

  • 安裝vue-cli
cnpm instal1 vue-cli-g
#測試是否安裝成功#查看可以基於哪些模板創建vue應用程序,通常我們選擇webpack
vue list

C:\Users.......\AppData\Roaming\npm\node_modules

image-20211113170836729

第一個vue項目

1、創建一個vue項目一路選no

C:\Users\CengXingPeng\Desktop\vue>vue init webpack myvue

? Project name myvue			//項目名字
? Project description A Vue.js project  //一個vue項目
? Author newcxp		//作者名
? Vue build standalone
? Install vue-router? No
? Use ESLint to lint your code? No
? Set up unit tests No
? Setup e2e tests with Nightwatch? No
? Should we run `npm install` for you after the project has been created? (recommended) no

   vue-cli · Generated "myvue".

# Project initialization finished!
# ========================

To get started:

  cd myvue
  npm install (or if using yarn: yarn)
  npm run dev

Documentation can be found at https://vuejs-templates.github.io/webpack


2、初始化vue項目

​ cd myvue
npm install (or if using yarn: yarn)
npm run dev

運行成功

PS C:\Users\....\Desktop\vue\myvue> npm run dev

> myvue@1.0.0 dev
> webpack-dev-server --inline --progress --config build/webpack.dev.conf.js

(node:7752) [DEP0111] DeprecationWarning: Access to process.binding('http_parser') is deprecated.
(Use `node --trace-deprecation ...` to show where the warning was created)
 13% building modules 25/29 modules 4 active ...ingPeng\Desktop\vue\myvue\src\App.vue{ parser: "babylon" } is deprecated; we now treat it as { parser: "babel" }.
 95% emitting

 DONE  Compiled successfully in 3719ms                                                                                                                                       下午5:42:26

 I  Your application is running here: http://localhost:8080


修改端口號

image-20211113174607274

安裝WebPack

WebPack 是一款模塊加載器兼打包工具,它能把各種資源,如JS、JSX、ES6、SASS、LESS圖片等都作為模塊來處理和使用

npm install webpack -g
npm install webpack-cli -g

測試安裝是否成功

  • webpack -v
  • webpack-cli -v
  • image-20211113181452828

配置

創建webpack.config.js配置文件

  • entry: 入口文件,指定WebPack 用哪個文件作為項目的入口
  • output:輸出,指定WebPack 把處理完成的文件放置到指定路徑
  • module:模塊,用於處理各種類型的文件
  • plugins:插件,如:熱更新、代碼重用等
  • resolve:設置路徑指向
  • watch:監聽,用於設置文件改動后直接打包

使用Webpack

1、創建文件用IEDA打開

image-20211113181951840

2、創建一個名為modules的目錄。用於放置JS模塊等資源文件

3、在modules字下創建文件,如hello.js 用於編寫JS相關代碼

//暴露一個方法 sayhi
exports.sayhi=function (){
    document.write("<h1>hello webpack</h1>")
}

4、在modules目錄下創建一個main.js的入口文件用於打包是設置entry屬性

//暴露一個方法 sayhi
exports.sayhi=function (){
    document.write("<h1>hello webpack</h1>")

5、在項目目錄下創建webpack.config.js配置文件使用webpack命令打包

module.exports={
    entry:"./modules/main.js",
    output:{
        filename:"./js/bundle.js"
    },
    mode: 'development'//設置開發環境
};

注意:webpack.config.js文件中必須陪配置開發環境不然報錯mode: 'development'

運行過程

image-20211113190506694

image-20211113180824942

vue vue-router

​ Vue Router是 Vue.js官方的路由管理器。它和Vue.js的核心深度集成,讓構建單頁面應用變得易如反掌。包含的功能有:

  • 嵌套的路由/視圖表
  • 模塊化的。基於組件的路由配置
  • 路由的參數、查詢、通配符
  • 基於Vue.js過渡系統的視圖過渡效果
  • 細粒度的導航控制
  • 帶有自動激活的CSS class的鏈接
  • HTML5歷史模式或hash 模式,在IE9中自動降級自定義的滾動條行為

安裝

基於第一個vue-cli進行測試;先查看node_modules中是否存在vue-router

​ vue-router是一個插件包,所以我們還需要用npm/cnpm來進行安裝。打開命令行工具進入項目目錄輸入

npm install vue-router  --save-dev

如果在模塊工程中使用它,必須通過Vue.use()明確地安裝路由功能

import Vue from 'vue'
import VueRouter from 'vue-router'
//安裝路由
Vue.use(VueRouter)

測試 參考文檔(3條消息) 一篇文章,Vue快速入門!!!_cV展示的學習園-CSDN博客

Vue+elementUI

創建工程

注意命令行都要使用管理員模式運行

  1. 創建一個hello-vue工程 vue init webpack hello-vue
  2. 安裝依賴 vue-routerelementUIsass-loader、和node-sass
# 進入項目工程 
cd hello-vue
#安裝 vur-router
npm install vue-router  --saver-dev
# 安裝elementUI
npm i element-ui -s
#安裝依賴
npm install
#安裝SASS加載器
cnpm install sass-loader node-sass --save-dev
#啟動測試
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為該命令的縮寫
  1. 創建視圖字在views目錄下創建一個名為login.vue的視圖組件,其el-*的元素為ElementUI的組件

  2. 自動生成doc的網站文檔化 (docsify.js.org)

引入 Element

你可以引入整個 Element,或是根據需要僅引入部分組件。我們先介紹如何引入完整的 Element。

完整引入

在 main.js 中寫入以下內容:

import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import App from './App.vue'

Vue.use(ElementUI)

new Vue({
  el: '#app',
  render: h => h(App)
})

注意:運行報錯

image-20211113235711268

可能是sass版本過高需要回退版本

image-20211113235921293 image-20211114000028874

修改版本后從新npm install

#先卸載node-sass
npm uninstall node-sass
#再重裝4.x版本的node-sass
npm install node-sass@4.14.1

如果node.js版為16+ [https://blog.csdn.net/sinat_38592878/article/details/110387262]:用dart-sass(sass)代替

多路由嵌套

嵌套路由又稱子路由,在實際應用中,通常由多層嵌套的組件組合而成

  • 創建用戶信息組件,在 views/user 目錄下創建一個名為 Profile.vue 的視圖組件
<template>
  <h1>個人信息</h1>
</template>
<script>
  export default {
    name: "UserProfile"
  }
</script>
<style scoped>
</style>
  • 在用戶列表組件在 views/user 目錄下創建一個名為 List.vue 的視圖組件
<template>
  <h1>用戶列表</h1>
</template>
<script>
  export default {
    name: "UserList"
  }
</script>
<style scoped>
</style>

  • 修改首頁視圖,我們修改 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>

  • 添加了組件,去router修改配置文件
//導入vue
import Vue from 'vue';
import VueRouter from 'vue-router';
//導入組件
import Main from "../views/Main";
import Login from "../views/Login";
//導入子模塊
import UserList from "../views/user/List";
import UserProfile from "../views/user/Profile";

//使用
Vue.use(VueRouter);
//導出
export default new VueRouter({
  routes: [
    {
      //登錄頁
      path: '/main',
      component: Main,
      //  寫入子模塊
      children: [
        {
          path: '/user/profile',
          component: UserProfile,
        }, {
          path: '/user/list',
          component: UserList,
        },
      ]
    },
    //首頁
    {
      path: '/login',
      component: Login

    },
  ]
})


參數傳遞

第一種方式

頁面設置

 <el-menu-item index="1-1">
                <!--插入的地方-->
                <!--name是組件的名字 params是傳的參數 如果要傳參數的話就需要用v:bind:來綁定-->
                <router-link :to="{ name:'UsePersonal',params:{id:1}}">個人信息</router-link>
              </el-menu-item>

路由設置

 {
         path:"/user/usepersonal/:id",
          name: "UsePersonal",
          component:UsePersonal
        }

頁面渲染

<!-- 所有的內容都要寫在div中 -->
  <div>
    <h1>用戶信息</h1>
    {{$route.params.id}}
  </div>

第二種方式

頁面設置(props屬性設置為true)

 <el-menu-item index="1-1">
                <!--插入的地方-->
                <!--name是組件的名字 params是傳的參數 如果要傳參數的話就需要用v:bind:來綁定-->
                <router-link :to="{ name:'UsePersonal',params:{id:1},props:true}">個人信息</router-link>
              </el-menu-item>

路由設置props: true,

{
         path:"/user/usepersonal/:id",
          props: true,
          name: "UsePersonal",
          component:UsePersonal
        }

頁面渲染 props:['id']接收值

<template>
<!-- 所有的內容都要寫在div中 -->
  <div>
    <h1>用戶信息</h1>
    {{id}}
  </div>
</template>

<script>
export default {
  props:['id'],
  name: "UserPersonal"
  },

重定向 redirect:"/main"

  {
      //重定向
      path:"/gohome",
      redirect:"/main"
    },

路由模式和404

路由模式有兩種

  • hash:路徑帶#,如https://localhost/#/login
  • history:路徑不帶#號,如https://localhost/login
 mode:'history',
  routes:[
    {
      path:'/login',
      component:Login
    },

404頁面

  1. 創建一個NotFound.vue視圖
<template>
  <div>
    <h1>404,你的頁面走丟了</h1>
  </div>
</template>
<script>
    export default {
        name: "NotFound"
    }
</script>
<style scoped>
</style>
  1. 配置路由
import NotFound from '../views/NotFound'
{
   path: '*',
   component: NotFound
}

路由鈎子

除了之前的鈎子函數還存在兩個鈎子函數

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

參數說明

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

在組件中

<script>
    export default {
        name: "UserProfile",
        beforeRouteEnter: (to, from, next) => {
            console.log("准備進入個人信息頁");
            next();
        },
        beforeRouteLeave: (to, from, next) => {
            console.log("准備離開個人信息頁");
            next();
        }
    }
</script>

在鈎子函數中進行異步請求

  • 安裝axios
cnpm install --save vue-axios
  • main.js引用 Axios
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
  • 准備數據
{
  "name": "cv戰士",
  "url": "https://blog.csdn.net/qq_45408390?spm=1001.2101.3001.5343",
  "page": 1,
  "isNonProfit": true,
  "address": {
    "street": "含光門",
    "city": "陝西西安",
    "country": "中國"
  },
  "links": [
    {
      "name": "bilibili",
      "url": "https://bilibili.com"
    },
    {
      "name": "cv戰士",
      "url": "https://blog.csdn.net/qq_45408390?spm=1001.2101.3001.5343"
    },
    {
      "name": "百度",
      "url": "https://www.baidu.com/"
    }
  ]
}

說明: 只有我們的 static 目錄下的文件是可以被訪問到的,所以我們就把靜態文件放入該目錄下

  • 在 beforeRouteEnter 中進行異步請求
<script>
    export default {
        name: "UserProfile",
        beforeRouteEnter: (to, from, next) => {
            console.log("准備進入個人信息頁");
            next(vm => {
                //進入路由之前執行getData方法
                vm.getData()
            });
        },
        beforeRouteLeave: (to, from, next) => {
            console.log("准備離開個人信息頁");
            next();
        },
        //axios
        methods: {
            getData: function () {
                this.axios({
                    method: 'get',
                    url: 'http://localhost:8080/static/mock/data.json'
                }).then(function (response) {
                    console.log(response)
                })
            }
        }
    }
</script>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM