【Vue3】第三部分 setup的注意点

  • Post author:
  • Post category:vue




【Vue3】第三部分 setup的注意点





3. setup的注意点



3.1 执行的时机



beforeCreate

之前

setup

会执行一次,

setup



this



undefined

<template>
  <div>
    <h1>Welcome to learn about Vue3!</h1>
    <h2>name:{{person.name}}</h2>
    <h2>gender:{{person.gender}}</h2>
  </div>
</template>

<script>
import {reactive} from "vue"
export default {
    name:'TestDemo',
    setup(){
      const person = reactive({
        name:'Tree',
        gender:'male'
      })
      //1. setup执行时机在beforeCreate前
      console.log('----setup----',this);  //this是undefined

      return {
        person
      }

    },
    beforeCreate(){
      console.log('----beforeCreate----');
    }
}
</script>




3.2 setup的参数


setup

有两个参数分别是:

props



context


props:

  • 值为对象,组件外部传递进来,并且组件内部声明接收了的属性


context:


  • attrs

    :值为对象,组件外部传进来,但是

    没有被props配置

    中声明接收的属性,相当于

    this.$attrs

  • emit

    :分发自定义事件的函数,相当于

    this.$emit

  • slots

    :收到插槽内容,相当于

    this.$slots


TestDemo组件

<template>
  <div>
    <h1>Welcome to learn about Vue3!</h1>
    <h2>name:{{person.name}}</h2>
    <h2>gender:{{person.gender}}</h2>
    <h2>{{message}}</h2>
    <h2>{{hello}}</h2>
    <!-- 插槽 -->
    <slot name="here"></slot>
    <button @click="test">click me show</button>
  </div>
</template>

<script>
import {reactive} from "vue"
export default {
    name:'TestDemo',
    props:["message","hello"], //接收
    setup(props,context){
      const person = reactive({
        name:'Tree',
        gender:'boy'
      })
      console.log(props); 

      console.log(context.attrs);

      console.log(context.emit);

      console.log(context.slots);

      // 触发自定义事件
      function test(){
        context.emit('Test',person)
      }

      return {
        person,
        test
      }

    }
}
</script>



App组件

<template>
  <TestDemo
   message = "The basic information" 
   hello='Say Hello!'
   @Test = 'Demo'
   >
   <!-- <template slot="here"> -->
    <template v-slot:here>
        <h2> I am slot</h2>
    </template>
   </TestDemo>
</template>

<script>
import TestDemo from "./components/TestDemo.vue"
export default {
  name:'App',
  components:{TestDemo},
  setup(){
    function Demo (val){
      alert(`Hello!everyone! Myname is ${val.name},I am a lovely ${val.gender}!`)

    }

    return{
      Demo
    }
  }
}
</script>





总结

例如:以上就是今天要讲的内容,希望对大家有所帮助!!!



版权声明:本文为Trees__原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。