modal在html上渲染不出来

来源:3-17 Teleport - 瞬间移动 第一部分

weixin_慕无忌4335029

2022-06-27

index.html

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <div id="modal"></div>
  </body>
</html>

App.vue

<template>
  <div id="box"></div>
</template>

<script lang="ts">
import { defineComponent, onMounted, onUpdated, onRenderTriggered, onUnmounted } from 'vue'
import HelloWorldVue from './components/HelloWorld.vue'
import UseModal from './components/UseModal.vue'
export default defineComponent({
  components: {
    UseModal,
    HelloWorldVue
  },
  setup() {
    onMounted(() => {
      console.log('mounted')
    })
    onUpdated(() => {
      console.log('update')
    })
    onUnmounted(() => {
      console.log('unmount')
    })
    onRenderTriggered(event => {
      console.log('我触发了', event)
    })
  }
})
</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>

UseModal.vue

<template>
  <teleport to="#modal">
    <div id="center">
      <h2>this is a modal</h2>
    </div>
  </teleport>
</template>
<script lang="ts">
import { defineComponent,} from 'vue'
export default defineComponent({
})
</script>
<style>
#center {
  width: 200px;
  height: 200px;
  border: 2px solid black;
  background: white;
  position: fixed;
  left: 50%;
  top: 50%;
  margin-left: -100px;
  margin-top: -100px;
}
</style>

代码如上,app.vue里写了components组件,还是没法在html上渲染,请老师帮我看看。

写回答

1回答

张轩

2022-06-28

同学你好

你在 App 中引入了这个 component,但是需要在模版上使用啊,现在你在模版中并没有使用这个组件

<template>
  <div id="box"></div>
</template>
改为
<template>
  <div id="box">
    <use-modal/>
  </div>
</template>

试试看




1
0

Vue3 + TS 仿知乎专栏企业级项目

带你完成前后端分离复杂项目,率先掌握 vue3 造轮子技能

3142 学习 · 2313 问题

查看课程