vue3.0新特性 组合式API(setup)

组合式API

setup是个函数在props被解析完成后执行,setup(props,content)
1.props是响应式的,所以不能进行es6解构会失去响应式的特性.
note:可以使用toRefs函数完成次操作。

import { toRefs } from 'vue'
setup(props) {
    const { title } = toRefs(props)
    console.log(title.value)
}

2.context主要暴露四个属性

export default {
  setup(props, context) {
    // Attribute (非响应式对象,等同于 $attrs)
    console.log(context.attrs)

    // 插槽 (非响应式对象,等同于 $slots)
    console.log(context.slots)

    // 触发事件 (方法,等同于 $emit)
    console.log(context.emit)

    // 暴露公共 property (函数)
    console.log(context.expose)
  }
}

主要说下expose:
主要是将子组件的方法暴露出去,父组件通过ref去调用此方法.

//child.vue
  <template></template>
  <script>
  import { h } from 'vue'
    export default{
      const increment = () => ++count.value;
      ctx.expose({
        increment,
      });
      return () => h("div", count.value);
    }
  </script>
//parent.vue
  <template>
    <child ref="child" />
    <button @click="add">增加</button>
  </template>
  <script>
  import { ref } from 'vue'
  export default {
    setup(props, context) {
      const child = ref('null')
      const add = () => {
        child.value.increment();
      };
      return {child,add}
    }
  }
</script>

多个子组件

//parent.vue
  <template>
    <div  :key="index" v-for="(item, index) in 2">
      <child :ref="(el) => {child[index] = el}" />
      <button @click="add(index)">增加</button>
    </div>
  </template>
  <script>
  import { ref } from 'vue'
  export default {
    setup(props, context) {
      const child = ref({})
      const add = (i) => {
        child.value[i].increment();
      };
      return {child,add}
    }
  }
</script>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容