vue3 元件中props,emits用法

wuxing164發表於2020-11-11

 

元件
<template>
    <teleport to="#mymodel">
        <div id="center" v-if="isShow">
            <h2><slot>my model</slot></h2>
            <button @click="btnclose">close</button>
        </div>
    </teleport>
</template>

<script>
    import {defineComponent} from "vue"
    export default defineComponent ({
        props:{
            isShow:Boolean
        },
        emits:{
            "my-close":null
        },
        setup(props,context){
            const btnclose = ()=>{
                context.emit("my-close")
            }
            return{
                btnclose
            }
        }
    })
</script>

<style scoped>
    #center{
        width: 500px;
        height: 500px;
        position: fixed;
        left: 50%;
        top: 50%;
        background-color: antiquewhite;
        margin-left: -250px;
        margin-top: -250px;
    }
</style>
#使用元件
<template>
  <my-modal @my-close="myModealHide" :isShow="myModalShow">my model hehe</my-modal>
  <button @click="myModalBlock">my modal2</button>
</template>

<script lang="ts">
import { defineComponent,ref,computed,watch} from 'vue';
import Modal from "./components/Modal.vue"

export default defineComponent({
  name: 'App',
  components:{
    MyModal
  },
  setup() {
    const myModalShow = ref(false)
    const myModalBlock =()=>{
      myModalShow.value=true
    }
    const myModealHide=()=>{
      myModalShow.value=false
    }
    return {
      myModalShow,
      myModalBlock,
      myModealHide,
    }
  }

});
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

 

相關文章