ES6
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body><script>// 變量定義var a=1;let b=5; // 現在使用let 定義變量// 對象解構let person={"name":"dc","age":25}console.log(person.name); // 原操作:對象.屬性名console.log(person.age);let {name,age}=person; // 對象解構console.log(name);console.log(age);// 模板字符串let info=`你好,${name}。今年${age}歲`// promisefunction get(url) {return new Promise((resolve, reject) => {$.ajax({url: url,type: "GET",success(result) {resolve(result);},error(error) {reject(error);}});});}// Async函數async function func1() {// 業務、計算let x = 101;if (x % 2 === 0) {return x;} else {throw new Error("x不是偶數");}}func1().then(data => console.log("then", data)).catch(err => console.log("err", err)); // 調用func1// await + asyncasync function func2() {let x = await func1(); // await同步等待func1() 結果后 結束console.log("x", x);}func2();// ES6模塊化// user.jsconst user = {username: "張三",age: 18}function isAdult(age){if (age > 18) {console.log('成年人');} else {console.log('未成年');}}// main.js// exportexport { user, isAdult }import { user, isAdult } from './lib/user.js';isAdult(user.age);</script>
</body>
</html>
npm 包管理工具
Vue3
$ npm create viteNeed to install the following packages:create-vite
Ok to proceed? (y) y? Project name: · vite-project
? Select a framework: · vue
? Select a variant: · vueScaffolding project in ./vite-project...Done. Now run:cd vite-projectnpm installnpm run dev
cd vite-project
npm install
npm run dev
插值
<script setup>
let name = "張三"let car = {brand: "小米",price: 999
}
</script><template><!-- {{val}} 插值表達式,頁面任何位置取值--><h2>姓名:{{name}}</h2><h2>品牌:{{car.brand}}</h2><h2>價格:{{car.price}}</h2>
</template><style scoped>
</style>
常用指令
v-html
// 2. 指令
let msg = "<p style='color: red'>你好</p>"<template><h2>姓名:{{name}}</h2><h2>品牌:{{car.brand}}</h2><h2>價格:{{car.price}}</h2><div v-html="msg"></div>
</template>
<script setup>// 指令: v-xxx;
// 基礎指令: v-html、v-text
// 事件指令: v-onlet msg = "<p style='color: red'>你好</p>";function buy() {alert("購買成功");
}</script><template><h2>姓名:{{name}}</h2><h2>品牌:{{car.brand}}</h2><h2>價格:{{car.price}}</h2><button @click="buy">購買</button><div v-html="msg"></div><div>{{msg}}</div><div v-text="msg"></div></template>
v-if 、v-for
<span style="color: green" v-if="car.price < 1000"> 便宜</span>
<span style="color: red" v-if="car.price >= 1000"> 太貴</span>
<li v-for="(f, i) in fruits">{{ f }} ==> {{ i }}</li>
v-bind
<script>
// 3. 屬性綁定:v-bind
let url = "https://www.baidu.com";
</script><template><a v-bind:href="url">Go !</a>
</template>
響應式變化:數據的變化 可以更新到頁面效果上 ref()、reactive()
<script>// 3. 屬性綁定:v-bind;默認數據 不具備響應式特性let url = ref("https://www.example.com");// 響應式特性:數據的變化 可以更新到頁面效果上function changeUrl() {console.log(url);// 改變的時候需要 url.valueurl.value = "https://www.atguigu.com";}// ref():// 1. 把基本數據使用 ref() 包裝成響應式數據// 2. 使用 代理對象.value = ""// 3. 頁面取值、屬性綁定 直接 {{url}}// 傳遞對象reactive()const money = reactive({money: 1000,name: "parent",});</script><template><a :href="url" :abc="url">Go ! {{ url }}</a><button @click="changeUrl">改變地址</button>
</template>
表單綁定 v-model :雙向綁定
<script setup>
import { reactive } from "vue";const data = reactive({username: "zhangsan",agree: true,hobby: [],gender: "女",degree: "",course: []
})
</script><template><p style="background-color: azure"><label>姓名(文本框):</label><input v-model="data.username"/></p>
</template>
計算屬性
<script setup>import { ref, computed } from 'vue';// 假設 car 和 num 是已經定義的響應式對象或引用const car = {price: 10000 // 示例價格};const num = ref({ value: 1 }); // 示例數量// 計算總價const totalPrice = computed(() => car.price * num.value);</script><template><!-- <button v-on:click="buy">購買</button> --><button @click.once="buy">購買 {{ totalPrice }}</button>
</template>
監聽 watch()
<script>const num = ref({ value: 1 });// 監聽: watch/watchEffect// num數字發生變化時,開啟回調函數watch(num, (value, oldValue, onCleanup) => {console.log("value", value);console.log("oldValue", oldValue);if (num.value > 3) {alert("超出限購數量");num.value = 3;}});</script>
<script>// 監聽一堆事件watchEffect(() => {if (num.value > 3) {alert("超出限購數量");num.value = 3;}if (car.price > 11000) {alert("太貴了");}});</script>
生命周期 mounted()
<script setup>import { ref, onMounted } from 'vue';// 定義一個響應式變量 countconst count = ref(0);// 假設 elementId 是一個已定義的元素 IDconst elementId = "ds";// onMounted 生命周期鉤子onMounted(() => {console.log("掛載完成!!!")});
</script>
組件傳值
父傳子
v-bind
Son
<script setup>
// 1、定義屬性
let props = defineProps( ['money'] );</script><template><div style="background-color: #646cff; color: white;"><h3>Son</h3><!-- 只讀值 read only--><div>賬戶:{{ props.money }}</div></div>
</template><style scoped>
</style>
Father
<script setup>
import Son from "./Son.vue";
import { ref } from "vue";// 1、父傳子,單向數據流,子變了 父親的不會變
const money = ref(100);</script><template><div style="background-color: #f9f9f9"><h2>Father</h2><!-- 屬性綁定傳遞值--><Son :money="money" /></div>
</template><style scoped>
</style>
let props = defineProps({money: {type: Number,required: true,default: 200},books: Array
});
子傳父
emit
<script setup>
import Son from "./Son.vue";// 1、父傳子
const data = reactive({money: 1000,name: "parent",
});function moneyMinis(arg) {// alert("感知到兒子買了棒棒糖" + arg)data.money += arg;
}</script><template><div style="background-color: #f9f9f9"><h2>Father</h2><Son :money="data.money" @buy="moneyMinis"/><!-- <Son v-bind="data"/> --></div>
</template><style scoped>
</style>
<script setup>// 1、定義屬性
let props = defineProps( ['money'] );
// 2、使用 emit: 定義事件
const emits = defineEmits(['buy']);function buy() {// props.money -= 5; // 這里不直接修改 props,而是通過 emit 通知父組件emits('buy', -5);
}
</script><template><div style="background-color: #646cff; color: white"><h3>Son</h3><div>賬戶:{{ props.money }}</div><button @click="buy">買棒棒糖</button></div>
</template><style scoped>
</style>
插槽
Father
<script setup>
</script><template><div style="background-color: #f9f9f9"><h2>Father</h2><Son ><template v-slot:title>哈哈SonSon</template></Son></div>
</template><style scoped>
</style>
Son
<script setup>
</script><template><div style="background-color: #646cff; color: white"><h3><slot name="title">哈哈Son</slot></h3><button @click="buy"><slot name="btn"/></button></div>
</template><style scoped>
</style>
Vue - Router
npm install vue-router
在 src/router/index.js 中配置路由:
index.js
// 引入必要的模塊
import { createRouter, createWebHashHistory } from 'vue-router';
import Home from '../views/Home.vue'; // 假設 Home 組件位于 views 文件夾下
import Hello from '../views/Hello.vue'; // 假設 Hello 組件位于 views 文件夾下// 定義路由規則
const routes = [{ path: '/', component: Home },{ path: '/hello', component: Hello },{path: '/haha',component: () => import('../views/Haha.vue') // 動態導入 Haha 組件}
];// 創建路由器
const router = createRouter({history: createWebHashHistory(), // 使用 hash 模式routes // 路由規則
});// 導出路由器
export default router;
在 src/main.js 中使用路由器:
main.js
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router'let app = createApp(App);// 1、使用 router
app.use(router)
app.mount('#app');
在 App.vue 中使用 和
<template><router-link to="/">首頁</router-link><router-link to="/hello">Hello</router-link><router-link to="/haha">Haha</router-link><!-- ... --><hr /><router-view></router-view><!-- ... --><!-- 1、整合 vue-router --><!-- 2、配置 vue-router --><!-- 配置路由表 --><!-- 創建路由器 --><!-- 3、Vue 實例使用 router --><!-- 4、配置 router-link 和 router-view -->
</template>
Axios
發送請求
App.vue
<script setup>
import axios from 'axios'function getInfo() {axios.get("http://43.139.239.29/get").then(resp => {console.log(resp.data);// config: 請求配置// data: 服務器的響應數據 √√√// headers: 響應頭// request: 請求對象// status: 響應狀態碼// statusText: 響應描述文本})
}function getInfoParam() {axios.get("http://43.139.239.29/get", {params: {id: 1,username: 'zhangsan'}}).then(resp => {console.log(resp);});
}function postInfoParam() {// 數據會被自動轉為jsonaxios.post("http://43.139.239.29/post",{id: 222,username: 'zhangsan',age: 18}).then(resp => {console.log(resp);});
}</script><template><button @click="getInfo">GET請求</button><button @click="getInfoParam">GET請求 帶參數</button><button @click="postInfoParam">POST 請求</button>
</template><style scoped>
</style>
實例配置
index.js
import axios from 'axios';const http = axios.create({baseURL: 'http://43.139.239.29',timeout: 1000,headers: { 'X-Custom-Header': 'foobar' }
});export default http;
App.vue
<script setup>
import http from './index'function getInfo() {http.get("/get").then(resp => {console.log(resp.data);// config: 請求配置// data: 服務器的響應數據 √√√// headers: 響應頭// request: 請求對象// status: 響應狀態碼// statusText: 響應描述文本})
}</script><template><button @click="getInfo">GET請求</button>
</template><style scoped>
</style>
攔截器
index.js
import axios from 'axios';// 創建自定義 Axios 實例
const http = axios.create({baseURL: 'http://43.139.239.29',timeout: 1000,headers: { 'X-Custom-Header': 'foobar' }
});// 添加請求攔截器
http.interceptors.request.use(function (config) {// 在發送請求之前做些什么return config;},function (error) {// 對請求錯誤做些什么console.log("請求錯誤", error);return Promise.reject(error);}
);// 添加響應攔截器
http.interceptors.response.use(function (response) {// 2xx 范圍內的狀態碼都會觸發該函數。// 對響應數據做點什么// 返回響應數據主體內容return response.data;},function (error) {// 超出 2xx 范圍的狀態碼都會觸發該函數。// 對響應錯誤做點什么console.log("響應錯誤", error);ElMessage.error("服務器錯誤" + error.message); // 使用 Element UI 的 Message 組件顯示錯誤消息return Promise.reject(error);}
);// 導出 http 實例
export default http;
Pinia
類似后端的Redis
npm install pinia
money.js
import { defineStore } from 'pinia';// 定義一個 money存儲單元
export const useMoneyStore = defineStore('money', {state: () => ({ money: 100 }),getters: {rmb: (state) => state.money,usd: (state) => state.money * 0.14,eur: (state) => state.money * 0.13,},actions: {win(arg) {this.money += arg;},pay(arg) {this.money -= arg;}},
});
Wallet.vue
<script setup>
import { useMoneyStore } from './money.js'
let moneyStore = useMoneyStore();
</script><template><div><h2>¥: {{moneyStore.rmb}}</h2><h2>$: {{moneyStore.usd}}</h2><h2>€: {{moneyStore.rmb}}</h2></div>
</template><style scoped>
div {background-color: #f9f9f9;
}
</style>
game.vue
<script setup>
import { useMoneyStore } from './money.js';let moneyStore = useMoneyStore();function guaguale() {moneyStore.win(100);
}function bangbang() {moneyStore.pay(5);
}
</script><template><button @click="guaguale">刮刮樂</button><button @click="bangbang">買棒棒糖</button>
</template><style scoped>
</style>