本文代码地址

Vue 3.0 新增一个叫 Teleport 的 api,使用它可以让我们的组件模板插入到根节点 #app 以外的元素节点中去。

基本使用

创建 TeleportTest 组件,其中 to 就是你需要指向到任意位置的 Dom

  1. <template>
  2. <teleport to="#login">
  3. <div v-if="visible">
  4. <div class="modal">Modal 弹出来了</div>
  5. <button @click="onClick">关闭</button>
  6. </div>
  7. </teleport>
  8. </template>
  9. <script>
  10. import { ref } from 'vue'
  11. import { useLogin } from '../hooks'
  12. export default {
  13. props: {
  14. visible: Boolean
  15. },
  16. methods: {
  17. onClick() {
  18. this.$emit('update:visible', false)
  19. }
  20. },
  21. }
  22. </script>

在 index.html 中新增节点

  1. <body>
  2. <div id="app"></div>
  3. <div id="login"></div> // 新增节点
  4. <script type="module" src="/src/main.js"></script>
  5. </body>

App.vue 中引入组件

  1. <template>
  2. <div>
  3. <button class="loginer" @click="onLogin">Modal 框</button>
  4. <TeleportTest v-model:visible="visible"/>
  5. </div>
  6. </template>
  7. <script>
  8. import TeleportTest from './components/TeleportTest.vue'
  9. import { useLogin } from './hooks'
  10. export default {
  11. components: {
  12. TeleportTest
  13. },
  14. setup() {
  15. const { onLogin, visible } = useLogin();
  16. return {
  17. visible,
  18. onLogin
  19. }
  20. }
  21. }
  22. </script>

新建 hooks 逻辑

  1. // hooks.js
  2. import { ref } from 'vue'
  3. export const useLogin = () => {
  4. const visible = ref(false);
  5. const onLogin = (type) => {
  6. console.log(type);
  7. visible.value = true;
  8. console.log(visible);
  9. }
  10. const onClose = () => {
  11. visible.value = false;
  12. }
  13. return {
  14. visible,
  15. onLogin,
  16. onClose
  17. }
  18. }

实现效果如下:
1212.gif