2.5 年经验总结的 6 个 VueJs 基本技巧 #1

2025-06-04

2.5 年经验总结的 6 个 VueJs 基本技巧 #1

嘿,你好吗?欢迎来到我这里,我叫 Code Oz,我会和你分享一些关于 VueJs 的技巧(我使用这个框架有 2.5 年的经验)。

始终在 props 上使用验证器,以检查从父级传递给子级的值是否正确

    props: {
        toto: {
            type: String,
            required: true,
            validator: function (val) {
                return [ 'a', 'b' ].includes(val)
            }
        }
    },
Enter fullscreen mode Exit fullscreen mode

如果验证器检测到错误,vue 将触发 Vue Warn!

初始化时触发观察器

watch: {
    toto: (newValue, oldValue) => {
        // logic here ...
    }
}
Enter fullscreen mode Exit fullscreen mode

⚠️ 这将在发生改变时触发toto,但不会在初始化时触发。

如果您想在初始化阶段触发观察者,您可以使用immediate属性!

watch: {
    toto: {
      immediate: true,
      handler(newValue, oldValue) {
        // logic here ...
      }
    }
}
Enter fullscreen mode Exit fullscreen mode

Handler是当属性被修改时触发的函数。

动态应用类和样式

<div :style="{ 'background': isActivated ? 'black' : 'white' }">
Enter fullscreen mode Exit fullscreen mode

您还可以仅当值为 true 时应用类/样式!

// If isActivated is false, class will be not applied
<div :class="{ 'toto-class': isActivated }">
Enter fullscreen mode Exit fullscreen mode

切勿将 V-if 与 V-for 一起使用

永远不会!为什么?

当你这样做的时候👇

<li v-for="todo in todos" v-if="!todo.isComplete">
  {{ todo }}
</li>
Enter fullscreen mode Exit fullscreen mode

当您在同一个节点中使用两者时,的优先级高于v-for因此将在的每次迭代中触发v-ifv-ifv-for

为了避免这种情况,你可以用👇替换你的代码

<ul v-if="todos.length">
    <li v-for="todo in todos">
    {{ todo }}
    </li>
</ul>
Enter fullscreen mode Exit fullscreen mode

但是如果您想使用v-ifforisComplete属性,最好的方法是根据条件创建一个计算。

computed: {
    todosNotCompleted() {
        return this.todos.filter(todo => !todo.isComplete)
    },
}
Enter fullscreen mode Exit fullscreen mode
<ul v-if="todos.length">
    <li v-for="todo in todosNotCompleted">
    {{ todo }}
    </li>
</ul>
Enter fullscreen mode Exit fullscreen mode

你可以将所有道具从父母传递给孩子

<child-component v-bind="$props"></child-component >
Enter fullscreen mode Exit fullscreen mode

V 模型

v-model 是一个用于在组件上创建双向数据绑定的指令!

<input v-model="message" placeholder="edit me">
Enter fullscreen mode Exit fullscreen mode

这等于

<input :value="message" @input="message = $event.target.value" placeholder="edit me">
Enter fullscreen mode Exit fullscreen mode

当您需要更新一个值或当该值改变时发出一个值时,使用它作为简写!

希望你喜欢这些技巧!这些都是基础知识,之后我会分享更多关于 Vuejs 的技巧(更高级的)!


我希望你喜欢这篇文章!

🎁 如果您在TwitterUnderrated skills in javascript, make the difference上关注我并给我点赞,即可免费获得我的新书😁

或者在这里获取

🎁我的新闻通讯

☕️ 你可以支持我的作品🙏

🏃‍♂️ 你可以关注我 👇

🕊 推特:https://twitter.com/code__oz

👨‍💻 Github:https://github.com/Code-Oz

你也可以标记🔖这篇文章!

文章来源:https://dev.to/codeoz/6-essentials-tips-for-vuejs-from-2-5-years-experience-1-4h7o
PREV
Vue 学院 #1:作用域样式
NEXT
React 中的 prop 钻孔是什么?