前端vue3Vue3必学的12个JS前置知识,零基础也能懂
星野暗涌🚀 为什么需要学Vue3?
Vue3是目前最流行的前端框架之一,学习它有以下几个重要原因:
1. 市场需求旺盛
2. 学习曲线友好
中文文档完善,对中国开发者友好
渐进式框架设计,可以逐步深入学习
社区活跃,学习资源丰富
3. 开发效率高
4. 性能优秀
虚拟DOM优化,渲染速度快
按需编译,打包体积小
支持Tree-shaking,减少冗余代码
5. 职业发展
掌握Vue3可以开发企业级应用
为学习React、Angular等框架打下基础
可以转向全栈开发(配合Node.js)
💡 Vue3技术为什么会诞生?
理解Vue3的诞生背景,有助于我们更好地掌握它的设计理念和核心特性。
Vue2遇到的瓶颈
在Vue3诞生之前,Vue2已经非常成熟并被广泛使用。但随着前端应用越来越复杂,Vue2逐渐暴露出一些问题:
1. 大型项目代码组织困难
2. TypeScript支持不够友好
Vue2使用基于类的组件实现,类型推导困难
this的类型推导存在局限
大型团队协作时类型安全得不到保障
3. 性能优化空间有限
4. 移动端和跨平台支持受限
Vue3的技术革新
为了解决这些问题,尤雨溪和Vue核心团队从2018年开始重写Vue,经过2年多的开发,于2020年9月发布了Vue3。
核心改进:
1. 组合式API(Composition API)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| export default { data() { return { count: 0, user: {} } }, methods: { increment() { this.count++ }, fetchUser() { } }, computed: { doubleCount() { return this.count * 2 } } }
import { ref, computed } from 'vue'
export default { setup() { const count = ref(0) const doubleCount = computed(() => count.value * 2) const increment = () => count.value++ const user = ref({}) const fetchUser = () => { } return { count, doubleCount, increment, user, fetchUser } } }
|
2. 更好的TypeScript支持
完全用TypeScript重写
类型推导更准确
开发体验大幅提升
3. 性能提升
4. 新的核心特性
Teleport(传送门)组件
Fragments(多根节点)
Suspense(异步组件处理)
更好的自定义渲染器API
5. 生态系统升级
Vue3的技术目标
Vue3的设计遵循以下原则:
✅ 向下兼容 - 保持Vue的核心理念,降低迁移成本
✅ 更快更小 - 性能优化和打包体积优化
✅ 更好的开发体验 - TypeScript支持、更好的调试工具
✅ 面向未来 - 为未来的Web标准和需求做准备
📖 引言
如果你准备学习Vue3,那么扎实的JavaScript基础是必不可少的。Vue3的组合式API(Composition API)、响应式系统、组件通信等核心特性,都建立在现代JavaScript(ES6+)的基础之上。
本文将系统梳理Vue3开发中高频使用的12个JavaScript核心知识点,每个知识点都配有完整的代码示例、详细解析和Vue3应用场景说明。无论你是前端新手还是想快速入门Vue3,这篇文章都能帮你打下坚实的JS基础。 🤗
1️⃣ 变量和常量(let/const)
核心概念
ES6引入了let和const来声明变量,替代传统的var,解决了变量提升、块级作用域等问题。
代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| let count = 0; count = 1;
const MAX_COUNT = 100; MAX_COUNT = 200;
if (true) { let blockVar = 'block'; const BLOCK_CONST = 'const'; } console.log(blockVar);
const user = { name: '张三', age: 25 }; user.age = 26; user = {};
const arr = [1, 2, 3]; arr.push(4); arr = [];
|
Vue3中的应用
1 2 3 4 5 6 7 8 9
| import { ref, reactive } from 'vue';
const count = ref(0); const state = reactive({ name: 'Vue3' });
const increment = () => { count.value++; };
|
🤔 思考问题
Q:为什么const声明的对象可以修改属性,但不能重新赋值?
A:const保证的是变量指向的内存地址不变,而不是值不变。对于引用类型(对象、数组),变量存储的是内存地址(指针),所以可以修改对象内部的属性,但不能让变量指向新的对象。
1 2 3 4 5
| const obj = { a: 1 };
obj.a = 2; obj = { a: 2 };
|
⚠️ 注意事项
2️⃣ 模板字符串
核心概念
模板字符串使用反引号 `包裹,支持嵌入表达式和多行文本,比传统字符串拼接更简洁易读。
代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| const name = 'Vue3'; const version = 3.4; const message1 = '欢迎学习 ' + name + ' 版本 ' + version;
const message2 = `欢迎学习 ${name} 版本 ${version}`;
const html = ` <div class="container"> <h1>${name}</h1> <p>版本:${version}</p> </div> `;
const price = 100; const discount = 0.8; const finalPrice = `最终价格:${price * discount}元`;
const greeting = `你好,${name.toUpperCase()}!`;
|
与普通字符串的区别
| 特性 |
普通字符串 |
模板字符串 |
| 包裹符号 |
' 或 " |
` |
| 多行文本 |
需要用n或字符串拼接 |
直接换行 |
| 嵌入变量 |
需要用+拼接 |
${变量} |
| 嵌入表达式 |
不支持 |
${表达式} |
Vue3中的应用
1 2 3 4 5 6 7 8 9 10 11 12
| const isActive = true; const className = `btn ${isActive ? 'active' : ''}`;
<template> <div>{{ `用户:${user.name},年龄:${user.age}` }}</div> </template>
const userId = 123; router.push(`/user/${userId}`);
|
⚠️ 注意事项
模板字符串使用反引号 ,不是单引号‘`
模板字符串会保留空格和换行
核心概念
对象是JavaScript中最重要的数据结构,掌握对象的取值、赋值和简写规则是必备技能。
3.1 点取值 vs 中括号取值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| const user = { name: '张三', age: 25, 'home-address': '北京' };
console.log(user.name);
console.log(user['name']); console.log(user['home-address']);
const key = 'age'; console.log(user[key]);
const formData = { username: 'admin', password: '123456' }; const fields = ['username', 'password']; fields.forEach(field => { console.log(formData[field]); });
|
3.2 属性和方法的简写
4.1 数组解构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| const colors = ['red', 'green', 'blue']; const [first, second, third] = colors; console.log(first); console.log(second);
const [r, , b] = colors; console.log(r, b);
const numbers = [1, 2, 3, 4, 5]; const [one, two, ...rest] = numbers; console.log(one, two); console.log(rest);
const [x = 10, y = 20] = [1]; console.log(x, y);
|
4.2 对象解构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| const user = { name: '张三', age: 25, city: '北京' }; const { name, age } = user; console.log(name, age);
const { name: userName, age: userAge } = user; console.log(userName, userAge);
const { name, age, gender = '未知' } = user; console.log(gender);
const { name, ...rest } = user; console.log(rest);
const student = { name: '李四', score: { math: 90, english: 85 } }; const { name, score: { math, english } } = student; console.log(math, english);
|
4.3 函数参数解构
核心概念
箭头函数是ES6引入的简洁函数写法,在Vue3中大量使用,尤其是在事件处理、计算属性、侦听器中。
语法规则
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| function add(a, b) { return a + b; }
const add = (a, b) => { return a + b; };
const double = x => x * 2;
const add = (a, b) => a + b;
const greet = () => console.log('Hello');
const getUser = () => ({ name: '张三', age: 25 });
const wrong = () => { name: '张三' };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <template> <button @click="() => count++">点击</button> <button @click="increment">点击</button> </template>
<script setup> import { ref } from 'vue';
const count = ref(0); const increment = () => { count.value++; }; </script>
const doubleCount = computed(() => count.value * 2);
watch(count, (newVal, oldVal) => { console.log(`从${oldVal}变为${newVal}`); });
onMounted(() => { console.log('组件已挂载'); });
|
⚠️ 注意事项
6️⃣ 数组的重要方法
6.1 修改原数组的方法
1 2 3 4 5 6 7 8 9 10 11 12 13
|
const arr = [1, 2, 3]; const newLength = arr.push(4, 5); console.log(arr); console.log(newLength);
const todos = ref([]); const addTodo = (text) => { todos.value.push({ id: Date.now(), text, done: false }); };
|
1 2 3 4 5 6
|
const arr = [1, 2, 3]; arr.unshift(0); console.log(arr);
|
1 2 3 4 5 6 7
|
const arr = [1, 2, 3]; const last = arr.pop(); console.log(arr); console.log(last);
|
1 2 3 4 5 6 7
|
const arr = [1, 2, 3]; const first = arr.shift(); console.log(arr); console.log(first);
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
const arr = [1, 2, 3, 4, 5];
arr.splice(1, 2); console.log(arr);
arr.splice(1, 0, 'a', 'b'); console.log(arr);
arr.splice(1, 2, 'x'); console.log(arr);
const deleteItem = (index) => { list.value.splice(index, 1); };
|
6.2 不修改原数组的方法
1 2 3 4 5 6 7 8 9 10
|
const arr = [1, 2, 3]; console.log(arr.includes(2)); console.log(arr.includes(5));
const permissions = ['read', 'write']; const canDelete = permissions.includes('delete');
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
const arr = [1, 2, 3]; arr.forEach((item, index) => { console.log(`索引${index}:${item}`); });
users.value.forEach(user => { user.isSelected = false; });
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
const numbers = [1, 2, 3]; const doubled = numbers.map(n => n * 2); console.log(doubled);
const users = [ { id: 1, name: '张三' }, { id: 2, name: '李四' } ]; const names = users.map(user => user.name); console.log(names);
const formattedUsers = computed(() => { return users.value.map(user => ({ ...user, fullName: `${user.firstName} ${user.lastName}` })); });
|
1 2 3 4 5 6 7 8 9
|
const numbers = [2, 4, 6, 8]; const allEven = numbers.every(n => n % 2 === 0); console.log(allEven);
const allValid = formFields.every(field => field.value.trim() !== '');
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
const numbers = [1, 2, 3, 4]; const sum = numbers.reduce((acc, cur) => acc + cur, 0); console.log(sum);
const max = numbers.reduce((acc, cur) => Math.max(acc, cur)); console.log(max);
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']; const count = fruits.reduce((acc, fruit) => { acc[fruit] = (acc[fruit] || 0) + 1; return acc; }, {}); console.log(count);
const totalPrice = computed(() => { return cart.value.reduce((total, item) => { return total + item.price * item.quantity; }, 0); });
|
6.3 对象的重要方法
Object.keys() / values() / entries()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const user = { name: '张三', age: 25, city: '北京' };
const keys = Object.keys(user); console.log(keys);
const values = Object.values(user); console.log(values);
const entries = Object.entries(user); console.log(entries);
|
结合数组方法遍历对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| const scores = { math: 90, english: 85, chinese: 88 };
Object.keys(scores).forEach(subject => { console.log(`${subject}: ${scores[subject]}分`); });
const total = Object.values(scores).reduce((sum, score) => sum + score, 0); console.log(total);
const highScores = Object.entries(scores) .filter(([subject, score]) => score >= 88) .map(([subject, score]) => subject); console.log(highScores);
|
Vue3应用场景
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| const formData = reactive({ username: '', password: '', email: '' });
const validateForm = () => { return Object.keys(formData).every(key => { return formData[key].trim() !== ''; }); };
const columns = { name: '姓名', age: '年龄', city: '城市' };
<template> <table> <tr> <th v-for="(key, value) in columns" :key="key"> {{value}} </th> </tr> </table> </template>
|
8️⃣ 扩展运算符(…)
核心概念
扩展运算符(Spread Operator)用三个点...表示,可以展开数组或对象,常用于复制、合并和解决引用类型赋值问题。
8.1 复制数组/对象
1 2 3 4 5 6 7 8 9 10 11 12
| const arr1 = [1, 2, 3]; const arr2 = [...arr1]; arr2.push(4); console.log(arr1); console.log(arr2);
const user = { name: '张三', age: 25 }; const copiedUser = { ...user }; copiedUser.age = 26; console.log(user.age);
|
8.2 合并数组/对象
1 2 3 4 5 6 7 8 9 10 11
| const arr1 = [1, 2]; const arr2 = [3, 4]; const merged = [...arr1, ...arr2]; console.log(merged);
const defaults = { theme: 'light', lang: 'zh' }; const userSettings = { theme: 'dark' }; const settings = { ...defaults, ...userSettings }; console.log(settings);
|
8.3 同名属性覆盖规则
1 2 3 4 5 6 7 8 9 10
| const obj1 = { a: 1, b: 2 }; const obj2 = { b: 3, c: 4 }; const merged = { ...obj1, ...obj2 }; console.log(merged);
const user = { name: '张三', age: 25 }; const updatedUser = { ...user, age: 26, city: '北京' }; console.log(updatedUser);
|
8.4 解决引用类型赋值问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| const obj1 = { name: '张三' }; const obj2 = obj1; obj2.name = '李四'; console.log(obj1.name);
const obj1 = { name: '张三' }; const obj2 = { ...obj1 }; obj2.name = '李四'; console.log(obj1.name);
const user = { name: '张三', address: { city: '北京' } }; const copiedUser = { ...user }; copiedUser.address.city = '上海'; console.log(user.address.city);
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| const deepCopiedUser1 = JSON.parse(JSON.stringify(user));
function deepClone(obj) { if (obj === null || typeof obj !== 'object') return obj; if (obj instanceof Array) return obj.map(item => deepClone(item)); if (obj instanceof Object) { const newObj = {}; for (let key in obj) { if (obj.hasOwnProperty(key)) { newObj[key] = deepClone(obj[key]); } } return newObj; } } const deepCopiedUser2 = deepClone(user);
|
Vue3应用场景
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const state = ref({ count: 0, name: 'Vue' }); state.value = { ...state.value, count: state.value.count + 1 };
const formData = reactive({ name: '', age: 0 }); const defaultData = { name: '', age: 0 }; const resetForm = () => { Object.assign(formData, { ...defaultData }); };
router.push({ name: 'UserDetail', params: { ...user } });
|
9️⃣ 序列化和反序列化(JSON)
核心概念
代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| const user = { name: '张三', age: 25, hobbies: ['读书', '旅游'] };
const jsonStr = JSON.stringify(user); console.log(jsonStr);
console.log(typeof jsonStr);
const jsonStr = '{"name":"张三","age":25}'; const obj = JSON.parse(jsonStr); console.log(obj); console.log(typeof obj);
const formatted = JSON.stringify(user, null, 2); console.log(formatted);
|
使用场景
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| const obj1 = { name: '张三', age: 25 }; const obj2 = JSON.parse(JSON.stringify(obj1)); obj2.name = '李四'; console.log(obj1.name);
const obj = { func: () => {}, date: new Date(), undef: undefined, sym: Symbol('test') }; const copied = JSON.parse(JSON.stringify(obj)); console.log(copied);
localStorage.setItem('user', JSON.stringify(user)); const savedUser = JSON.parse(localStorage.getItem('user'));
|
Vue3应用场景
1 2 3 4 5 6 7 8 9 10 11 12
| const createUser = async (userData) => { const response = await fetch('/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(userData) }); const result = await response.json(); return result; };
|
🔟 Web存储(localStorage/sessionStorage)
核心概念
浏览器提供了两种Web存储方式:
基本用法
1 2 3 4 5 6 7 8 9
| localStorage.setItem('username', '张三'); const username = localStorage.getItem('username'); localStorage.removeItem('username'); localStorage.clear();
sessionStorage.setItem('token', 'abc123'); const token = sessionStorage.getItem('token');
|
存储引用类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| const user = { name: '张三', age: 25 };
localStorage.setItem('user', user);
localStorage.setItem('user', JSON.stringify(user));
const userStr = localStorage.getItem('user'); const user = JSON.parse(userStr); console.log(user);
const storage = { set(key, value) { localStorage.setItem(key, JSON.stringify(value)); }, get(key) { const value = localStorage.getItem(key); return value ? JSON.parse(value) : null; }, remove(key) { localStorage.removeItem(key); }, clear() { localStorage.clear(); } };
storage.set('user', { name: '张三', age: 25 }); const user = storage.get('user');
|
localStorage vs sessionStorage
| 特性 |
localStorage |
sessionStorage |
| 存储时效 |
永久存储,除非手动删除 |
关闭标签页后清除 |
| 作用域 |
同源窗口共享 |
仅当前标签页 |
| 容量限制 |
约5MB |
约5MB |
| 使用场景 |
用户偏好、登录状态 |
临时数据、表单草稿 |
Vue3应用场景
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| const token = ref(localStorage.getItem('token') || '');
const login = async (username, password) => { const res = await api.login(username, password); token.value = res.token; localStorage.setItem('token', res.token); };
const logout = () => { token.value = ''; localStorage.removeItem('token'); };
const theme = ref(localStorage.getItem('theme') || 'light');
watch(theme, (newTheme) => { localStorage.setItem('theme', newTheme); });
const cacheKey = 'user-list'; const users = ref([]);
onMounted(() => { const cached = localStorage.getItem(cacheKey); if (cached) { users.value = JSON.parse(cached); } else { fetchUsers(); } });
const fetchUsers = async () => { users.value = await api.getUsers(); localStorage.setItem(cacheKey, JSON.stringify(users.value)); };
|
⚠️ 注意事项
1️⃣1️⃣ Promise 与 Async/Await
核心概念
异步编程是JavaScript的重点难点,Vue3中的数据请求、延时操作都基于Promise和Async/Await。
11.1 回调地狱问题
1 2 3 4 5 6 7 8
| getUserInfo(userId, (user) => { getOrders(user.id, (orders) => { getOrderDetail(orders[0].id, (detail) => { console.log(detail); }); }); });
|
11.2 Promise基础
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
const promise = new Promise((resolve, reject) => { setTimeout(() => { const success = true; if (success) { resolve('成功的数据'); } else { reject('失败的原因'); } }, 1000); });
promise .then(data => { console.log(data); return data + '1'; }) .then(data => { console.log(data); }) .catch(error => { console.error(error); }) .finally(() => { console.log('无论成功失败都会执行'); });
|
11.3 Promise链式调用消除回调地狱
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| function getUserInfo(userId) { return new Promise((resolve) => { setTimeout(() => resolve({ id: userId, name: '张三' }), 1000); }); }
function getOrders(userId) { return new Promise((resolve) => { setTimeout(() => resolve([{ id: 1, name: '订单1' }]), 1000); }); }
function getOrderDetail(orderId) { return new Promise((resolve) => { setTimeout(() => resolve({ id: orderId, price: 100 }), 1000); }); }
getUserInfo(123) .then(user => { console.log('用户信息:', user); return getOrders(user.id); }) .then(orders => { console.log('订单列表:', orders); return getOrderDetail(orders[0].id); }) .then(detail => { console.log('订单详情:', detail); }) .catch(error => { console.error('出错了:', error); });
|
11.4 Async/Await - 异步终极解决方案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| async function fetchUser() { return { name: '张三' }; }
fetchUser().then(user => console.log(user));
async function getUser() { const user = await getUserInfo(123); console.log(user); }
async function loadData() { try { const user = await getUserInfo(123); console.log('1. 用户信息:', user); const orders = await getOrders(user.id); console.log('2. 订单列表:', orders); const detail = await getOrderDetail(orders[0].id); console.log('3. 订单详情:', detail); return detail; } catch (error) { console.error('出错了:', error); } finally { console.log('请求完成'); } }
loadData();
|
Vue3应用场景
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| import { ref, onMounted } from 'vue';
const users = ref([]); const loading = ref(false); const error = ref(null);
onMounted(async () => { loading.value = true; try { const response = await fetch('/api/users'); users.value = await response.json(); } catch (err) { error.value = err.message; } finally { loading.value = false; } });
const submitForm = async () => { const valid = await validateForm(); if (!valid) return; const result = await api.createUser(formData); if (result.success) { ElMessage.success('创建成功'); } };
const loadPageData = async () => { const [users, posts, comments] = await Promise.all([ api.getUsers(), api.getPosts(), api.getComments() ]); };
|
⚠️ 注意事项
1️⃣2️⃣ ES6模块化
核心概念
模块化可以将代码拆分成多个文件,提高可维护性和复用性。Vue3项目全部采用ES6模块化。
模块化的意义
1 2 3 4 5 6 7 8 9 10 11 12 13
|
function add() {} function subtract() {}
export function add(a, b) { return a + b; } export function subtract(a, b) { return a - b; }
import { add } from './utils/math.js';
|
package.json配置
1 2 3 4 5
| { "name": "my-project", "type": "module", "version": "1.0.0" }
|
⚠️ 注意:添加"type": "module"后,.js文件才能使用ES6模块语法(Node.js环境)。
默认导出/导入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| export default { name: '张三', age: 25, greet() { console.log(`你好,我是${this.name}`); } };
const user = { name: '张三', age: 25 }; export default user;
import user from './user.js'; import myUser from './user.js'; console.log(user.name);
|
按需导出/导入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| export const PI = 3.14;
export function add(a, b) { return a + b; }
export function multiply(a, b) { return a * b; }
const PI = 3.14; function add(a, b) { return a + b; } function multiply(a, b) { return a * b; } export { PI, add, multiply };
import { PI, add } from './utils.js'; console.log(PI); console.log(add(1, 2));
import { add as sum } from './utils.js'; console.log(sum(1, 2));
import * as utils from './utils.js'; console.log(utils.PI); console.log(utils.add(1, 2));
|
混合导出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| export const VERSION = '1.0.0';
export function formatUser(user) { return `${user.name} (${user.age}岁)`; }
export default { name: '张三', age: 25 };
import user, { VERSION, formatUser } from './user.js'; console.log(user); console.log(VERSION); console.log(formatUser(user));
|
Vue3应用场景
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| import { ref, reactive, computed, watch, onMounted } from 'vue';
import MyButton from './components/MyButton.vue'; import MyInput from './components/MyInput.vue';
import { formatDate, debounce } from '@/utils/index.js';
import * as userApi from '@/api/user.js';
import { ref } from 'vue';
export function useCounter(initialValue = 0) { const count = ref(initialValue); const increment = () => count.value++; const decrement = () => count.value--; return { count, increment, decrement }; }
import { useCounter } from '@/composables/useCounter.js'; const { count, increment } = useCounter(10);
|
🎯 知识点总结
恭喜你完成了Vue3前置JavaScript知识的学习!让我们回顾一下12个核心知识点:
| 知识点 |
核心要点 |
Vue3应用频率 |
| 1. let/const |
块级作用域、const修饰引用类型 |
⭐⭐⭐⭐⭐ |
| 2. 模板字符串 |
包裹、${}`嵌入表达式 |
⭐⭐⭐⭐ |
| 3. 对象操作 |
点取值/中括号取值、属性方法简写 |
⭐⭐⭐⭐⭐ |
| 4. 解构赋值 |
数组/对象解构、剩余运算符 |
⭐⭐⭐⭐⭐ |
| 5. 箭头函数 |
简洁语法、this继承 |
⭐⭐⭐⭐⭐ |
| 6. 数组方法 |
map/filter/reduce/forEach等 |
⭐⭐⭐⭐⭐ |
| 7. Object方法 |
keys/values/entries |
⭐⭐⭐⭐ |
| 8. 扩展运算符 |
...复制/合并 |
⭐⭐⭐⭐⭐ |
| 9. JSON序列化 |
stringify/parse |
⭐⭐⭐ |
| 10. Web存储 |
localStorage/sessionStorage |
⭐⭐⭐⭐ |
| 11. Promise/Await |
异步编程 |
⭐⭐⭐⭐⭐ |
| 12. ES6模块化 |
导出/导入 |
⭐⭐⭐⭐⭐ |
📚 学习建议
如何实操练习
1. 搭建练习环境
2. 每日一练(2周计划)
第1-3天:let/const、模板字符串、对象操作
第4-6天:解构赋值、箭头函数
第7-9天:数组方法(重点练习map/filter/reduce)
第10-11天:扩展运算符、JSON、Web存储
第12-14天:Promise/Async/Await、ES6模块化
3. 实战项目练习
重点掌握内容(Vue3高频)
必须熟练掌握(⭐⭐⭐⭐⭐):
const/let的使用
对象解构赋值
箭头函数
数组方法:map、filter、forEach
扩展运算符
Async/Await
ES6模块化
需要理解(⭐⭐⭐⭐):
模板字符串
对象方法(Object.keys等)
Promise链式调用
localStorage存储
下一步:开始学Vue3
完成这些前置知识后,你已经具备了学习Vue3的基础。建议按以下顺序学习:
1. Vue3基础
2. Vue3组件
组件注册和使用
Props和Emits
插槽(Slots)
3. Vue3进阶
组合式函数(Composables)
生命周期钩子
路由(Vue Router)
状态管理(Pinia)
💡 推荐资源:
🚀 结语
JavaScript是前端开发的基石,而这12个知识点是Vue3开发的”高频词汇”。不要追求一次性全部掌握,而是要在实践中反复练习,遇到不懂的就回来复习。
记住:看懂代码 ≠ 会写代码。动手练习才是王道!
祝你学习顺利,早日成为Vue3高手!💪