Skip to content

搞英语 → 看世界

翻译英文优质信息和名人推特

Menu
  • 首页
  • 作者列表
  • 独立博客
  • 专业媒体
  • 名人推特
  • 邮件列表
  • 关于本站
Menu

Vue中created和mounted有什么区别?

Posted on 2022-05-16

NpN8WH8v6CfA6j7dKAzuoiE5Lit2-5na3kxc.jpe

\ 在谈论 Vue 中的生命周期钩子时,大多数人会感到困惑的一件事是created和mounted之间的区别。他们都有相似的名字,他们觉得他们应该做同样的事情,但有一些细微的差别。

\

Vue中created和mounted的区别

首先, created()和mounted()都可以访问原型上的数据和道具。

\ 例如,这两个钩子都会在下面控制台记录“我的消息”,以及myProp的默认值,即“某些道具”:

\

 export default { data() { return { msg: 'My Message' } }, props: { myProp: { type: String, default: 'Some Prop' } }, created() { console.log(this.msg); console.log(this.myProp); }, mounted() { console.log(this.msg); console.log(this.myProp); } }

\

用于created和mounted的 Prop 继承

created()和mounted()之间的根本区别是您还没有访问created()中的DOM。

\

即使你设置了一个属性,它在created()和mounted()中仍然可用

\ 在上面的例子中,如果我们尝试引用this.$el ,它会在created()中返回null ,它会在mounted()中返回 DOM 元素:

\

 export default { created() { // Returns null console.log(this.$el); }, mounted() { // Returns the DOM element in console: console.log(this.$el); } }

\ 因此,任何 DOM 操作,甚至使用querySelector之类的方法获取 DOM 结构都将在created()中不可用。

\ created()非常适合调用 API,而mounted()非常适合在 DOM 元素完全加载后执行任何操作。

\

组合 API 并创建或挂载

对此的一个警告是,如果您使用的是 Composition API, created() ,实际上beforeCreated()不再存在。您必须改用setup() 。此函数代替created()和beforeCreated() 。

\ 因此,DOM 在setup()中仍然不可用。在 Composition API 中, mounted()保持不变。


也在这里发布

原文: https://hackernoon.com/what-is-the-difference-between-the-created-and-mounted-in-vue?source=rss

本站文章系自动翻译,站长会周期检查,如果有不当内容,请点此留言,非常感谢。
  • Abhinav
  • Abigail Pain
  • Adam Fortuna
  • Alberto Gallego
  • Alex Wlchan
  • Answer.AI
  • Arne Bahlo
  • Ben Carlson
  • Ben Kuhn
  • Bert Hubert
  • Bits about Money
  • Brian Krebs
  • ByteByteGo
  • Chip Huyen
  • Chips and Cheese
  • Christopher Butler
  • Colin Percival
  • Cool Infographics
  • Dan Sinker
  • David Walsh
  • Dmitry Dolzhenko
  • Dustin Curtis
  • Elad Gil
  • Ellie Huxtable
  • Ethan Marcotte
  • Exponential View
  • FAIL Blog
  • Founder Weekly
  • Geoffrey Huntley
  • Geoffrey Litt
  • Greg Mankiw
  • Henrique Dias
  • Hypercritical
  • IEEE Spectrum
  • Investment Talk
  • Jaz
  • Jeff Geerling
  • Jonas Hietala
  • Josh Comeau
  • Lenny Rachitsky
  • Liz Danzico
  • Lou Plummer
  • Luke Wroblewski
  • Matt Baer
  • Matt Stoller
  • Matthias Endler
  • Mert Bulan
  • Mostly metrics
  • News Letter
  • NextDraft
  • Non_Interactive
  • Not Boring
  • One Useful Thing
  • Phil Eaton
  • Product Market Fit
  • Readwise
  • ReedyBear
  • Robert Heaton
  • Rohit Patel
  • Ruben Schade
  • Sage Economics
  • Sam Altman
  • Sam Rose
  • selfh.st
  • Shtetl-Optimized
  • Simon schreibt
  • Slashdot
  • Small Good Things
  • Taylor Troesh
  • Telegram Blog
  • The Macro Compass
  • The Pomp Letter
  • thesephist
  • Thinking Deep & Wide
  • Tim Kellogg
  • Understanding AI
  • 英文媒体
  • 英文推特
  • 英文独立博客
©2025 搞英语 → 看世界 | Design: Newspaperly WordPress Theme