vue3.x 学习整理(二)

306 阅读1分钟

又搬了一天砖,摸鱼时间小小学习总结一下 ☺

Composition API

vue2.x中,所有的数据都在data方法中定义返回,方法定义在methods下面,并通过this调用

vue3.x中,所有的代码逻辑将在setup方法中实现,并且不再有this

那么如何来访问上下文呢?

getCurrentInstance

<script>
import { getCurrentInstance } from 'vue'

export default {
    name: 'Test'
    setup() {
        // ctx 开发环境可以访问到,生产环境不行
        // proxy 则都可以
        // const { ctx } = getCurrentInstance()
        const { proxy } = getCurrentInstance()
        console.log(proxy)
        return {}
    }
}
</script>

可以看到打印出来的结果,包含上下文参数及数据!

1622447290(1).jpg

Fragment(片段)

2.x中,vue template只允许有一个根节点
    <template>
      <div id="app">
      </div>
    </template>
3.x中,vue template支持多个根节点

    <template>
      <div id="app">
      </div>
      <div id="app1">
      </div>
    </template>

Teleport(传送门)

新增了一个内置组件:Teleport;这个组件的作用主要用来将模板内的 DOM 元素移动到页面的其他位置。代码如下:

    <body>
        <div id="app">
          <h3>Tooltips with Vue 3 Teleport</h3>
        </div>
        <-- to="#tobody" 需要移动到的位置 -->
        <div id="tobody"></div>
    </body>


    <template>
        <-- to="#tobody" 需要移动到的id -->
        <teleport to="#tobody">
          <div class="box">
            ...
          </div>
        </teleport>
    </template>

    <script>
        import { ref } from 'vue'

        export default {
          setup() {}
            return {}
          }
        }
    </script>

Suspense

它允许我们的应用程序在等待异步组件时渲染一些其它内容,让用户有一个更好体验。

以前,在Vue2中,我们必须使用条件判断(例如 v-if、 v-else等)来检查我们的数据是否已加载并显示一些其它内容。

但是现在,Vue3有Suspense了,因此我们不必担心跟踪何时加载数据并呈现相应的内容。

(1)使用 <Suspense></Suspense> 包裹所有异步组件相关代码 包裹所有异步组件相关代码

(2)<template #default></template> 插槽包裹异步组件

(3)<template #fallback></template> 插槽包裹渲染异步组件渲染之前的内容

vue2.x

    <template>
      <div>
        <div v-if="!loading">
          ...
        </div>
        <div v-if="loading">Loading...</div>
      </div>
    </template>

vue3.x

    <template>
      <div id="app">
        <Suspense>
          <template #default>
            <Async></Async>
          </template>
          <template #fallback>
            <h1>Loading...</h1>
          </template>
        </Suspense>
      </div>
    </template>

    <script>
    import Async from "./components/Async.vue";

    export default {
      name: "App",
      components: {
        Async
      }
    };
    </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>

咦,下班时间到了,今天学习总结到这里吧,未来可期,加油! 1622455760(1).png