setup配置项


  1. 理解:Vue3.0中一个新的配置项,值为一个函数。

  2. setup是所有Composition API(组合API)“ 表演的舞台 ”

  3. 组件中所用到的:数据、方法等等,均要配置在setup中。

  4. setup函数的两种返回值:

    1. 若返回一个对象,则对象中的属性、方法, 在模板中均可以直接使用。(重点关注!)

    2. 若返回一个渲染函数:则可以自定义渲染内容。(了解)

  5. 注意点:

    1. 尽量不要与Vue2.x配置混用

      • Vue2.x配置(data、methos、computed...)中可以访问到setup中的属性、方法。

      • 但在setup中不能访问到Vue2.x配置(data、methos、computed...)。

      • 如果有重名, setup优先。

    2. setup不能是一个async函数,因为返回值不再是return的对象, 而是promise, 模板看不到return对象中的属性。(后期也可以返回一个Promise实例,但需要Suspense和异步组件的配合)

 

<template>
  <!-- vue3组件中的模板结构可以没有根标签 -->
  <h1>一个人的信息</h1>
  <h2>{{name}}</h2>
  <h2>{{age}}</h2>
  <button @click="sayHello">说话</button>
</template>

<script>

export default {
  name: 'App',
  setup() {
    //数据,定义变量
    let name='张三'
    let age=20

    //方法
    function sayHello(){
      alert(`我是${name},今年${age}岁了`)
    }

    //setup的返回值,返回一个对象
    return{
      name,age,sayHello
    }

  }
 
}
</script>

<style>

</style>

 

注意点

  • setup执行的时机

    • 在beforeCreate之前执行一次,this是undefined。

  • setup的参数

    • props:值为对象,包含:组件外部传递过来,且组件内部声明接收了的属性。

    • context:上下文对象

      • attrs: 值为对象,包含:组件外部传递过来,但没有在props配置中声明的属性, 相当于 this.$attrs

      • slots: 收到的插槽内容, 相当于 this.$slots

      • emit: 分发自定义事件的函数, 相当于 this.$emit

Demo.vue

<template>
  <!-- vue3组件中的模板结构可以没有根标签 -->
  <h1>App传过来的信息</h1>
  <h2>{{msg1}}</h2>
  <h2>{{msg2}}</h2>
  <slot name="demoSlot">222</slot>
  <br>
  <button @click="sayHello">点击触发自定义事件</button>

</template>

<script>
import {reactive} from 'vue'

export default {
  name: 'Demo',
  props:['msg1','msg2'],
  emits:['hello'],
  setup(props,context) {
    console.log(props)
    console.log(context.slots)

    //方法
    function sayHello(){
      context.emit('hello',666)
    }

    //setup的返回值,返回一个对象
    return{
      sayHello
    }

  }
 
}
</script>

<style>

</style>

app.vue

<template>
  <Demo msg1="你好啊" msg2="helloVue3" @hello="helloApp">
    <template v-slot:demoSlot>
      <span>我是一个插槽</span>
    </template>
  </Demo>
</template>

<script>
import Demo from './components/Demo'

export default {
  name: 'App',
  components:{
    Demo
  },
  setup() {
    function helloApp(value){
      console.log(`触发了自定义事件,参数是${value}`);
    }

    return {
      helloApp
    }
  }
 
}
</script>

<style>

</style>

 

posted @ 2023-07-08 19:34  Mr_sven  阅读(12)  评论(0编辑  收藏  举报