vue-cli vue mounted created 每次 调用_[Vue] 2 - 生命周期 / 组件通信 / computed vs watch

555a64f2c4caf91011097dc67a09ec7c.png

1 - Vue 生命周期

vue 有: created、mounted、updated、destroyed 每个生命周期前面都有beforeXxx()

  • 创建实例前后,beforeCreate(), created()
  • mounted 前后,beforeMount(), mounted() (异步请求在mounted调用)
  • 数据变化 前后,beforeUpdate(), updated()
  • 结束 前后,beforeDestroy(), destroyed()
LIN.JY666:[React] 2 - 生命周期​zhuanlan.zhihu.com
90d91de4d6af9cdb5ceda4c828163b47.png

1c63f06fda1d02ec858cc29fe8cd287a.png
<template>
  <div id="hello">
    <h1>{{ msg }}</h1>
    <input v-model="input" placeholder="edit me">
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      input: '123'
    }
  },

  beforeCreate () {
    console.log('beforeCreate', this)
    console.log(this.$el) // undefined
    console.log(this.$data) // undefined
    console.log(this.input) // undefined
  },

  created () {
    console.log('created')

    console.log(this.$el) // undefined
    console.log(this.$data) // {__ob__: Observer} { input: "123" msg: "Welcome to Your Vue.js App" }
    console.log(this.input) // 123
  },

  beforeMount () {
    // render 之前
    console.log('beforeMount')
    console.log(this.$el) // undefined
    console.log(this.$data) // {__ob__: Observer} { input: "123" msg: "Welcome to Your Vue.js App" }
    console.log(this.input) // 123
  },

  mounted () {
    // 替换<div id="app"></div>后
    console.log('mounted')
    console.log(this.$el) // <div id="hello"><h1>Welcome to Your Vue.js App</h1> <input placeholder="edit me"></div>
    console.log(this.$data) // {__ob__: Observer} { input: "123" msg: "Welcome to Your Vue.js App" }
    console.log(this.input) // 123

    this.msg = 'title 测试'
  },

  beforeUpdate () {
    // 数据更新时调用,发生在虚拟 DOM 重新渲染和打补丁之前
    console.log('beforeUpdate') // this.msg = 'title 测试' 因为数据变化了, 所有触发了该流程
    // 此时还是 <div id="hello"><h1>Welcome to Your Vue.js App</h1> <input placeholder="edit me"></div>
  },

  updated () {
    console.log('updated')
    // <div id="hello"><h1>title 测试</h1> <input placeholder="edit me"></div>
  },

  // 实例销毁之前调用
  beforeDestroy () { console.log('beforeDestroy') },
  // 实例销毁
  destroyed () { console.log('destroyed') }
}
</script>

2 - 组件通信

LIN.JY666:[React] 7 - 组件通信

44b828c79231be5eec13c4ff5a7766e5.png

常见的几种模式:

  1. 父组件 => 子组件 props
  2. 子组件 => 父组件 $emit / v-on / 回调
  3. eventBus 类似 React用法 new EventEmitter() 订阅发布模式
  4. Vuex 全局管理

3 - computed vs watch?

  • computed: 计算某个值,并该值依赖其他数据。
  • watch: 值变化前后的观测。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值