美文网首页
异步组件——通过条件预先划定不同temp模板

异步组件——通过条件预先划定不同temp模板

作者: 弦生_a3a3 | 来源:发表于2022-03-22 11:34 被阅读0次

需求:有些组件需要的temp模板是根据父组件传进来不同的参数渲染不同的temp模板,和不同的data。此时异步组件就可以用到了

使用前,须知:

vue有两种形式的代码 compiler(模板)模式和runtime模式(运行时),vue模块的package.json的main字段默认为runtime模式, 指向了"dist/vue.runtime.common.js"位置

vue中runtimecompiler和runtimeonly的区别

开发中,你依然使用template,就需要选择runtimecompiler
开发中,使用的是.vue文件夹开发,那么可以选择runtimeonly

runtimecompiler

image.png

Vue中的模板如何最终渲染成真实DOM
template -> ast -> render -> vdom -> UI

runtimeonly

image.png

Vue中的模板如何最终渲染成真实DOM
render -> vdom -> UI

Vue默认走runtimecompiler形式.runtime-only比runtime-compiler更快,因为它省略了vue内部过程中的第一个过程,如果是runtime-compiler那么main.js中就会出现template从而需要过程一导致增加了一个过程,同时增加了大小而 runtime-only 模式中不是没有写 template ,只是把 template 放在了.vue 的文件中了并有一个叫 vue-template-compiler的在开发依赖时将.vue文件中的 template 解析成 render 函数了因为是开发依赖,不在最后生产中,所以最后生产出来的运行的代码没有template

如果需要用到extends或者异步组件提前划定不同temp就需要用到runtimeCompiler模式

解决方法在vue.config中增加个配置就可以了
runtimeCompiler: true

异步组件使用示例:

<template>
  <div>
    异步
    <async-demo  v-if="isShow"/>
  </div>
</template>

<script>
import Vue from 'vue';

export default {
  data(){
    return{
      isShow:false,
    }
  },
   mounted(){
       //此处先编辑号模板
        const Demo=Vue.component('async-demo',function(resolve,reject){
          resolve({
            template:`<div>{{name}}</div>`,
            data(){
              return {
                name:'测试'
              }
            },
          
          })
        })
        // 当为真时渲染异步组件
        this.isShow=true;
  }
}
</script>

<style>

</style>

渲染后:

image.png

相关文章