上一篇
晚上11点,办公室里只剩下你一个人,屏幕上的Vue组件报了一堆错误,老板明天早上还要看Demo,你揉了揉发酸的眼睛,心想:“这v-for
的key
到底该怎么写?为什么这个状态管理突然不更新了?”
别慌,这篇文章就是你的救星,咱们用最直白的大白话,把Vue开发中那些“一看就会,一写就废”的问题掰开揉碎讲清楚。
想象你搭积木:.vue
文件里<template>
是积木的形状,<script>
是积木的功能说明书,<style>
是给积木刷的油漆。
<template> <div class="cart"> <button @click="addToCart">加入购物车</button> </div> </template> <script> export default { methods: { addToCart() { console.log('老板说这个功能今晚必须上线') } } } </script> <style scoped> .cart button { background: pink; /* 产品经理说要少女心 */ } </style>
常见坑点:
scoped
样式有时不生效?试试>>>
深度选择器或:deep()
setup
语法糖时,记得<script setup>
里不用写return
双向绑定v-model
本质是语法糖:
<input :value="searchText" @input="searchText = $event.target.value" /> <!-- 等价于 --> <input v-model="searchText" />
诡异现象排查:
v-model
却忘了在data
里声明 v-model
要写modelValue
和update:modelValue
就像小区快递柜:
mutations
、actions
,适合大型项目 store.xxx = newValue
,更符合直觉 // 用Pinia写个计数器 export const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), actions: { increment() { this.count++ // 不用commit,直接改! } } })
血泪经验:
localStorage
或vuex-persistedstate
插件 computed
里直接修改store状态,会触发警告 像地铁线路图:
const routes = [ { path: '/user/:id', component: UserProfile, beforeEnter: (to) => { if (!isLogin) return '/login' // 拦截未登录用户 } } ]
高频问题:
key="$route.fullPath"
强制刷新 useRoute().params
,别在setup
外直接调用useRoute
<VirtualScroller :items="bigData" item-height="50" key-field="id" > <template #default="{ item }"> <div>{{ item.name }}</div> </template> </VirtualScroller>
<img v-lazy="imgUrl" placeholder="/loading.gif" />
const HeavyComponent = defineAsyncComponent(() => import('./HeavyComponent.vue') )
Cannot read property 'xxx' of undefined
解决方案:
<!-- 坏代码 --> <div>{{ user.info.address.street }}</div> <!-- 好代码 --> <div>{{ user?.info?.address?.street || '未知' }}</div>
Duplicate keys detected
真相:
<!-- 错误示范 --> <li v-for="item in items">{{ item }}</li> <!-- 正确姿势 --> <li v-for="(item, index) in items" :key="index + item.id"> {{ item }} </li>
Vue开发就像煮泡面——看起来简单,但要煮出米其林水准,火候、配料、时机一个都不能差,下次再遇到诡异bug时,记住三点:
v-for
没写key
v-bind
你可以自信地按下Ctrl+S
,让那个等待已久的Vue应用完美运行起来了。
本文由 琴星睿 于2025-08-01发表在【云服务器提供商】,文中图片由(琴星睿)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://vps.7tqx.com/wenda/500879.html
发表评论