 setup的两个注意点
setup的两个注意点
  # setup的两个注意点
- setup执行的时机
- 在beforeCreate之前执行一次,this是undefined。
 
- setup的参数
- props:值为对象,包含:组件外部传递过来,且组件内部声明接收了的属性。
- context:上下文对象
- attrs: 值为对象,包含:组件外部传递过来,但没有在props配置中声明的属性, 相当于 this.$attrs。
- slots: 收到的插槽内容, 相当于 this.$slots。
- emit: 分发自定义事件的函数, 相当于 this.$emit。
 
- attrs: 值为对象,包含:组件外部传递过来,但没有在props配置中声明的属性, 相当于 
 
// App.vue
<template>
  <Demo @hello="showHelloMsg" msg="你好啊" school="尚硅谷">
    <template v-slot:qwe>
      <span>hhhh</span>
    </template>
  </Demo>
</template>
<script>
import Demo from "./components/Demo";
export default {
  name: 'App',
  components: {Demo},
  setup(){
    function showHelloMsg(){
      alert(`你好啊`)
    }
    return {
      showHelloMsg
    }
  }
}
</script>
// Demo.vue
<template>
  <h1>一个人的信息</h1>
  <h2>姓名:{{ person.name }}</h2>
  <h2>年龄:{{ person.age }}</h2>
  <button @click="test">测试触发一下Demo组件的Hello事件</button>
</template>
<script>
import {reactive} from 'vue'
export default {
  name: 'Demo',
  props: ['msg', 'school'],
  emits: ['hello'],
  setup(props, context) {
    // console.log('setup', props)
    // console.log('setup', context)
    // console.log('setup', context.attrs) // 与Vue2的$attrs
    // console.log('setup', context.emit) // 触发自定义事件
    // console.log('setup', context.slots) // 插槽内容
      
    // 数据
    let person = reactive({
      name: '张三',
      age: '18',
    })
    function test() {
      context.emit('hello', 666)
    }
    // 返回一个对象(常用)
    return {
      person,
      test
    }
  },
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
上次更新: 2025/06/23, 07:26:12