Vue3.0学习二

组合式API:setup 在beforecreate之前就执行了。

import { ref, toRefs, toRef , h} from 'vue'

export  default {

  props:{

    name: { type: String }

  },

  //setup中使用props中的数据

  setup(props, context){

    //props

    console.log(props.name)

    //在setup中获取props的值且运用

    //const { 需要解构的属性 }

    const { name } = props //这样写不是响应式的要通过toRefs, 引用数据可以这样写

    const { name } = toRefs(props)

    //如果name是可选的prop,则传入的props中没有name。就要用toRef

    const { name } = toRef(props, 'name ')

    //context

    console.log(context.attrs.id) //abc, 相当于$attrs获取和返回属性值

    context.emit( '自定义方法名称',value  )  //相当于this.$emit

    //如果return是 return()=> h('div', '133')  这时候这个组件只显示return出来的,组件的方法和属性,可以通过context.expose({  })暴露出去。

    //子组件

    const counter = ref(20)

    function changeCounter(){

      counter.value++

    }

    context.expose({  counter, changeCounter  })

    //父组件

    let son = ref()

    console.log(son.value.counter)

    //父组件调用子直接的方法

    son.value.changeCounter()

    return {  }

   }

}

 父组件

<div>

  <son id="abc" ref="son"></son>

</div>

posted @ 2023-04-07 12:22  IT小兔  阅读(11)  评论(0)    收藏  举报
作者:IT小兔
出处:https://www.cnblogs.com/g-14

-------------------------------------------

个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!

如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!

万水千山总是情,打赏一分行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!