網(wǎng)站開(kāi)發(fā)的實(shí)訓(xùn)報(bào)告百度推廣平臺(tái)登錄網(wǎng)址
目錄
一、項(xiàng)目準(zhǔn)備
1.1、Vite搭建項(xiàng)目
1.2、vue_cli創(chuàng)建項(xiàng)目
二、組合式API(基于setup)
2.1、ref
2.2、reactive
2.3、toRefs
2.4、watch和watchEffect
2.5、computed
2.6、生命周期鉤子函數(shù)
2.7、setup(子組件)的第一個(gè)參數(shù)-props
2.8、setup(子組件)的第二個(gè)參數(shù)-context
2.8.1、context.attrs【$attrs】
2.8.2、context.slots【$slots】
2.8.3、context.emit【$emit】
2.8.4、context.expose
2.9、provide-inject
2.10、在單文件組件(SFC)中使用組合式API的編譯時(shí)語(yǔ)法糖
三、路由Vue-Router
3.1、引入和安裝
3.2、帶參數(shù)的動(dòng)態(tài)路由匹配
3.3、路由正則與重復(fù)參數(shù)
3.4、嵌套路由與重定向
3.5、替換頁(yè)面和堆棧中的前進(jìn)后退(js跳轉(zhuǎn))
3.6、路由組件傳參
3.7、路由懶加載
四、pinia
4.1、安裝
4.2、Option Store與Setup Store的定義與使用
4.3、State的基本使用
4.5、Getter的基本使用
4.6、Action的基本使用
4.7、Pinia與vuex的區(qū)別
一、項(xiàng)目準(zhǔn)備
1.1、Vite搭建項(xiàng)目
Vue3官網(wǎng)地址:快速上手 | Vue.js
Vite官網(wǎng)地址:開(kāi)始 | Vite 官方中文文檔
檢查自己電腦npm -v版本,按照以下命令自己選擇合適的命令
node -v檢查node版本>14.18,可以在官網(wǎng)自行下載Node.js
# npm 6.x
npm create vite@latest my-vue-app --template vue# npm 7+, extra double-dash is needed:
npm create vite@latest my-vue-app -- --template vue# yarn
yarn create vite my-vue-app --template vue# pnpm
pnpm create vite my-vue-app --template vue
注意:只有Node版本在14.18及以上,Vite搭建項(xiàng)目才能生效
創(chuàng)建好項(xiàng)目以后,可以在依賴(lài)包看一下,有沒(méi)有Vite,沒(méi)有就npm i一下,然后npm run dev,至此,項(xiàng)目創(chuàng)建成功!
1.2、vue_cli創(chuàng)建項(xiàng)目
先全局安裝了CLI,命令:npm install -g @vue/cli
檢查版本:vue --version
創(chuàng)建項(xiàng)目:vue create vue_app(項(xiàng)目名)
可以自定義:Manually select features?
選擇需要的css、router等,然后一直回車(chē),在項(xiàng)目終端npm run serve即可
二、組合式API(基于setup)
形式區(qū)別:Vue3采用組合式API;Vue2采用選項(xiàng)式API?。
組合式API:將同一個(gè)邏輯關(guān)注點(diǎn)的相關(guān)代碼收集在一起。
組件被創(chuàng)建之前執(zhí)行,不需要使用this,this不會(huì)指向?qū)嵗?/span>
2.1、ref
響應(yīng)式變量:通過(guò)引入ref定義響應(yīng)式變量,ref返回帶有value屬性的對(duì)象
在函數(shù)里進(jìn)行修改時(shí)要加.value
2.2、reactive
響應(yīng)式的引用類(lèi)型:通過(guò)引入reactive定義引用類(lèi)型的數(shù)據(jù)
2.3、toRefs
因?yàn)?#xff1a;ES6擴(kuò)展運(yùn)算符進(jìn)行解構(gòu)會(huì)使得對(duì)象中的屬性不是響應(yīng)式
所以:通過(guò)引入toRefs(object)函數(shù)使解構(gòu)后的數(shù)據(jù)重新獲得響應(yīng)式
vue2里是在data里進(jìn)行定義,而vue3以上內(nèi)容代碼演示如下:
<script>
import { ref, reactive, toRefs } from "vue";
export default {setup() {// 非響應(yīng)式(msg相關(guān)代碼)let msg = "hello";console.log(msg);function changeMsg() {msg = "nihao";console.log(msg); //nihao,但是視圖上不會(huì)改變}// 響應(yīng)式(counter相關(guān)代碼)// 通過(guò)引入ref定義響應(yīng)式變量【counter=0】,ref返回帶有value屬性的對(duì)象let counter = ref(0);function changeCounter() {counter.value++; //視圖上自加1}// 響應(yīng)式(obj相關(guān)代碼)// 通過(guò)引入reactive定義引用類(lèi)型的數(shù)據(jù)let obj = reactive({name: "張三",age: "19",children: {son: "小寶貝",},});function changeObj() {obj.name = "李四"; //視圖改變obj.children.name = "大王"; //視圖改變}// ES6擴(kuò)展運(yùn)算符進(jìn)行解構(gòu)會(huì)使得對(duì)象中的屬性不是響應(yīng)式// 故:通過(guò)引入toRefs(object)使解構(gòu)后的數(shù)據(jù)重新獲得響應(yīng)式return {msg,changeMsg,counter,changeCounter,obj,changeObj,...toRefs(obj),};},
};
</script>
<template><div><h1>{{ msg }}</h1><button @click="changeMsg">改變msg</button><hr /><h1>{{ counter }}</h1><button @click="changeCounter">改變counter</button><hr /><h1>{{ obj.name }}</h1><h1>{{ children.name }}</h1> <!-- 一開(kāi)始沒(méi)出現(xiàn),改變后才出現(xiàn)? --><button @click="changeObj">改變name</button></div>
</template>
2.4、watch和watchEffect
這兩個(gè)寫(xiě)在setup之內(nèi),return之前
watch和watchEffect區(qū)別:
(1)語(yǔ)法:
watch(監(jiān)聽(tīng)的響應(yīng)式變量,回調(diào)函數(shù))
watchEffect(回調(diào)函數(shù))
(2)作用:
watch監(jiān)聽(tīng)響應(yīng)式變量,無(wú)法監(jiān)聽(tīng)引用類(lèi)型;
watchEffect監(jiān)聽(tīng)引用類(lèi)型,不需要指定監(jiān)聽(tīng)屬性,組件初始化時(shí)會(huì)自動(dòng)收集依賴(lài)(執(zhí)行一次回調(diào)),只要屬性值發(fā)生改變,回調(diào)就會(huì)執(zhí)行。
import {watch, watchEffect } from "vue";
watch(counter, (newVal, oldVal) => {console.log("newVal", newVal);console.log("oldVal", oldVal);});
watchEffect(() => {console.log(obj.name);});
2.5、computed
輸出響應(yīng)式變量xxx.value,引用類(lèi)型不用加.value
import { ref,computed } from "vue"; let Msg = ref("hello");let reverMsg = computed(() => {return Msg.value.split("").reverse().join("");});console.log(reverMsg.value); //olleh
2.6、生命周期鉤子函數(shù)
在vue2基礎(chǔ)上加個(gè)on;setup本身就相當(dāng)于beforeCreate 和created;在頁(yè)面初始化時(shí),會(huì)執(zhí)行onBeforeMount、onMounted;數(shù)據(jù)發(fā)生變化時(shí),會(huì)執(zhí)行onBeforeUpdate、onUpdated;銷(xiāo)毀時(shí)執(zhí)行onBeforeUnmount、onUnmounted。
import { onBeforeMount, onBeforeUpdate, onMounted, onUpdated } from "vue";setup() {onBeforeMount(() => {console.log("onBeforeMount");//onBeforeMount});onMounted(() => {console.log("onMounted");//onMounted});onBeforeUpdate(() => {console.log("onBeforeUpdate");});onUpdated(() => {console.log("onUpdated");});},
2.7、setup(子組件)的第一個(gè)參數(shù)-props
? 父組件與子組件的傳值和vue2一樣,在子組件里面獲取父組件傳來(lái)的值,就是通過(guò)setup的第一個(gè)參數(shù)props獲取。值改變了,就在onUpdated里面獲取改變后的值。
2.8、setup(子組件)的第二個(gè)參數(shù)-context
2.8.1、context.attrs【$attrs】
Attribute 非響應(yīng)式對(duì)象
console.log(context.attrs);
//{class: 'classBox', id: 'IdBox', __vInternal: 1}
給組件上添加class/id,在子組件這邊可以拿到組件的類(lèi)名,然后做一些樣式操作
2.8.2、context.slots【$slots】
插槽 非響應(yīng)式對(duì)象
比如:context.slots.default() 判斷子組件標(biāo)簽類(lèi)型
2.8.3、context.emit【$emit】
(子組件觸發(fā)事件,等同于$emit)
2.8.4、context.expose
暴露公共 property,這樣子組件本身就是變成暴露的內(nèi)容,記得引入h
//通過(guò)expose暴露context.expose({counter,sendParent,});//返回渲染函數(shù) 沒(méi)有暴露數(shù)據(jù)return () => h("div", counter.value);
2.9、provide-inject
provide-inject用于跨組件傳值,如果想要響應(yīng)式改變,就要將值用rer/reactive進(jìn)行定義
2.10、在單文件組件(SFC)中使用組合式API的編譯時(shí)語(yǔ)法糖
總結(jié):
<script setup>相當(dāng)于setup() {}函數(shù)【頂層的綁定會(huì)被暴露給模板】
優(yōu)勢(shì):引入組件,不需要注冊(cè);定義變量、方法不需要暴露。
<script setup>
// 頂層的綁定會(huì)被暴露給模板
import { ref } from "vue";
// 引入組件,不需要注冊(cè)
import Hello from "./components/HelloWorld.vue";
// 定義變量、方法不需要暴露
const a = 20;
console.log(a);
const b = ref(10);
function addB() {b.value++;
}
</script>
<template><div><h2>{{ a }}</h2><h2>{{ b }}</h2><button @click="addB">改變B</button><Hello/></div>
</template>
三、路由Vue-Router
路由相關(guān)內(nèi)容地址:入門(mén) | Vue Router
3.1、引入和安裝
npm install vue-router@4? 或者? yarn add vue-router@4
在src包下新建router文件夾,在index.js里面引入配置的路徑
import { createRouter, createWebHashHistory } from 'vue-router'
// 1. 定義路由組件.也可以從其他文件導(dǎo)入
import Home from '../views/HomeView.vue'
import User from '../views/UserView.vue'
// 2. 定義一些路由,每個(gè)路由都需要映射到一個(gè)組件。
const routes = [{ path: '/', component: Home },{ path: '/user', component: User },
]
// 3. 創(chuàng)建路由實(shí)例并傳遞 `routes` 配置
const router = createRouter({// 4. 內(nèi)部提供了 history 模式的實(shí)現(xiàn)。為了簡(jiǎn)單起見(jiàn),我們?cè)谶@里使用 hash 模式。history: createWebHashHistory(),routes, // `routes: routes` 的縮寫(xiě)
})
export default router
main.js中進(jìn)行掛載
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
app.mount('#app')
路由跳轉(zhuǎn)運(yùn)用:
<router-link to="/">Go Home</router-link>
<router-link to="/user">Go User</router-link><!-- 路由出口 占位符 --><!-- 相當(dāng)于組件 路由匹配到的內(nèi)容頁(yè)面將渲染在這里 -->
<router-view></router-view>
3.2、帶參數(shù)的動(dòng)態(tài)路由匹配
路徑參數(shù)?用冒號(hào)表示? ? ?{ path: '/user/:id', component: User }
?<router-link to="/user/1234">Go User</router-link>
頁(yè)面獲取參數(shù):
Vue2: 在mounted里面通過(guò) this.$route.params.xx 獲取
vue3:引入useRoute,通過(guò)useRoute().params.xx獲取
<script setup>
import { useRoute } from "vue-router";
console.log(useRoute().params.id);
</script>
3.3、路由正則與重復(fù)參數(shù)
404頁(yè)面:
{ path: '/:path(.*)', component: NotFound },//使用正則,匹配任意的路徑,一般放最后
參數(shù)限制:
(1)動(dòng)態(tài)路由的參數(shù)一定是數(shù)字:{ path: '/about/:id(\\d+)', component: About };
(2)多個(gè)參數(shù):{ path: '/about/:id+', component: About };
(3)參數(shù)可有可無(wú),可以重復(fù)添加:{ path: '/about/:id*', component: About };
(4)參數(shù)可有可無(wú),不可以重復(fù)添加:{ path: '/about/:id?', component: About };
3.4、嵌套路由與重定向
children里面寫(xiě)要嵌套的路由。
{path: '/',redirect: '/home'? ? //重定向。下面肯定有這個(gè)路徑},
{ path: '/home', component: Home },
3.5、替換頁(yè)面和堆棧中的前進(jìn)后退(js跳轉(zhuǎn))
純js跳轉(zhuǎn)與帶對(duì)象跳轉(zhuǎn):path+query;name+params
頁(yè)面接收:this.$route.query.name。。。
this.$router.push("/xxx");
this.$router.push({path: "/xxx",query: {name: "zhangsan",},});
this.$router.push({name: "xxx",params: {name: "zhangsan",},});
//replace:true 替換當(dāng)前頁(yè)面
this.$router.replace({path: "/xxx",query: {name: "zhangsan",},});
this.$router.go(xx)? ? ? ? //正值為前進(jìn),負(fù)值為后退;
this.$router.back()? ? ? ? //后退,等于go(-1);
this.$router.forword()? ?//前進(jìn),等于go(1);
3.6、路由組件傳參
defineProps
3.7、路由懶加載
路由守衛(wèi)同vue2
將import ShopTwo from '../views/shop/ShopTwo.vue'
替換成const ShopTwo =()=>import("../views/shop/ShopTwo.vue")
達(dá)到"用到它時(shí)再加載"的效果
四、pinia
4.1、安裝
pinia官網(wǎng)地址:Pinia | The intuitive store for Vue.js
下載:npm install pinia
在main.js創(chuàng)建一個(gè)pinia實(shí)例:
4.2、Option Store與Setup Store的定義與使用
import { defineStore } from 'pinia'
// option store
export const useAgeStore = defineStore('dingding', {state: () => {//相當(dāng)于data屬性return { age: 30 }},getters: {//相當(dāng)于computed屬性gettersAge(state) {return state.age + 5}},actions: {//相當(dāng)于methods屬性addAge() {this.age++;//this指向?qū)?yīng)的store倉(cāng)庫(kù)}}
})
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
// setup store
export const useCounterStore = defineStore('main', () => {const counter = ref(30);//stateconst gettersCounter = computed(() => {//gettersreturn counter.value + 5})function addCounter() {//actionscounter.value++;}return { counter, gettersCounter, addCounter }
})
使用:
4.3、State的基本使用
? 為了完整類(lèi)似推理,推薦使用箭頭函數(shù),在Pinia中,state被定義為一個(gè)返回初始狀態(tài)的函數(shù),這使得Pinia可以同時(shí)支持服務(wù)端和客戶(hù)端。data(){return{}}防止數(shù)據(jù)污染(針對(duì)于服務(wù)端)。
<button @click="changeAge">修改age值</button>
<script setup>
import { useAgeStore } from "../stores/index.js";
const ageStore = useAgeStore();
// 修改state中的狀態(tài)
function changeAge() {// 方式一 直接修改ageStore.age++;ageStore.name = "張三豐";// 方式二 批量修改 $patch(對(duì)象) 建議使用ageStore.$patch({age: 40,name: "張三豐",arr: [...ageStore.arr, 5],});// 方式三 批量修改 $patch(函數(shù)) 強(qiáng)烈推薦ageStore.$patch((state) => {state.age = 40;state.name = "張三豐";state.arr.push(8);});// 方式四:在actions里面進(jìn)行修改
}
</script>
=============store中的state===================state: () => {//相當(dāng)于data屬性return { age: 30, name: '王富貴', arr: [1, 2, 3] }},
擴(kuò)展:(1)重置state:? xx.$reset();
? ? ? ? ? ?(2)監(jiān)聽(tīng)state:? xx.$subscribe();
4.5、Getter的基本使用
getters: {//相當(dāng)于computed屬性gettersAge(state) {return state.age + 5},// 通過(guò)this訪(fǎng)問(wèn)其他的getters,注意:不能使用箭頭函數(shù)gettersName(state) {return this.gettersAge + state.name},// 向getters傳遞參數(shù),返回函數(shù)的方式接收參數(shù),和普通函數(shù)一樣,沒(méi)有緩存的作用gettersAge(state) {return (data) => state.age + data},// 訪(fǎng)問(wèn)其他的store中的gettersgettersAge(state) {const counterStore = useCounterStore()return state.age + counterStore.gettersCounter},},
4.6、Action的基本使用
actions: {//相當(dāng)于methods屬性,既可以處理同步又可以處理異步addAge() {this.age++;//this指向?qū)?yīng)的store倉(cāng)庫(kù)},// 訪(fǎng)問(wèn)其他store中的actionsasync getList() {const counterStore = useCounterStore()if (counterStore.addCounter()) {let res = await axios.get('http://xxx').then(res => {console.log(res);})console.log(res);}}}
4.7、Pinia與vuex的區(qū)別
(1)Pinia搭配TS一起使用時(shí),有非常可靠的類(lèi)型推斷支持;
(2)Pinia沒(méi)有mutations,而actions的使用不同,在actions中可以處理同步也可以處理異步,getters的使用是一致的,state與vue2中data是相似的;
(3)Pinia沒(méi)有總?cè)肟谌悄K化,需要定義模塊名稱(chēng),當(dāng)多個(gè)模塊需要協(xié)作的時(shí)候,需要引入多個(gè)模塊;vuex是有總?cè)肟诘?#xff0c;在使用模塊化的時(shí)候不需要引入多個(gè)模塊;
(4)Pinia在修改狀態(tài)的時(shí)候不需要通過(guò)其他api,vuex需要通過(guò)commit、dispatch去修改,所以在語(yǔ)法上比vuex更容易理解和使用,靈活;
(5)Pinia就是更好的vuex,建議在項(xiàng)目中可以直接使用它了,尤其是使用了TS的項(xiàng)目。