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>
实例
点击不喝:
点击喝:
原创文章,作者:starterknow,如若转载,请注明出处:https://www.starterknow.com/126513.html