Vue3教程(对比vue2用法)

没啥好说的,淦就完事了,详见代码,里面有setup()用法和生命周期写法、父子组件的传值写法。

1、父组件

<template>
  <img src="./logo.png">
  <h1>Hello Vue 3!</h1>
  <button @click="inc">Clicked {{ count }} times.count++ {{auto}}</button>
  <child-node @my-emit="parentEmit"
              :data="order" />
</template>

<script>
//除去 beforeCreate 和 created 之外,在我们的 setup 方法中,有9个旧的生命周期钩子,我们可以在setup 方法中访问
//onBeforeMount
//onMounted
//onBeforeUpdate
//onUpdated
//onBeforeUnmount
//onUnmounted
//onActivated
//onDeactivated
//onErrorCaptured
//我们导入它们并在我们的代码中访问它们
import { onMounted, ref } from 'vue' //导入生命周期函数
import ChildNode from './chid.vue'
export default {
  components: {
    ChildNode
  },
  setup () {
    const count = ref(0)
    const inc = () => {
      count.value++
    }
    const order = ref('我是children,收到father下达的指令:今晚p酒')
    const parentEmit = (val) => {
      if (val) {
        order.value = "收到father下达的指令:你还是我儿子"
      } else {
        order.value = "father很生气:怂逼"
      }

    }
    const auto = ref(0)
    const autoadd = () => {
      setInterval(() => {
        auto.value++
      }, 1000)
    }
    onMounted(() => {
      autoadd()
    })

    return {
      count,
      inc,
      auto,
      order,
      parentEmit
    }
  }
}
</script>

<style scoped>
img {
  width: 200px;
}
h1 {
  font-family: Arial, Helvetica, sans-serif;
}
</style>

2、子组件

<template>
  <h1>{{data}}</h1>
  <button @click="childEmit(false)">上火了,不喝</button>
  <button style="margin-left:20px"
          @click="childEmit(true)"></button>
</template>

<script>
import { onMounted, ref } from 'vue'
export default {
  props: {
    data: {
      type: String,
    }
  },
  setup (props, { emit }) { //解构context,获取emit
    const childEmit = (params) => {
      emit('my-emit', params)
    }
    return {
      childEmit
    }

  }
}
</script>

<style scoped>
</style>

实例
在这里插入图片描述
点击不喝:
在这里插入图片描述
点击喝:
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

带风的少年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值