编程语言
首页 > 编程语言> > javascript-是否有可行的解决方案在Vue js中将组件模板拆分为多个部分?

javascript-是否有可行的解决方案在Vue js中将组件模板拆分为多个部分?

作者:互联网

我有一个组件,它根据props的值具有不同的模板内容.我觉得组件的结构还不够好,任何人都很难理解代码.如何将组件分成多个部分?

<template>
<div>
    <div v-if='config.isTag'>
       <!-- some 10 lines of code -->
        <span 
            v-if="ok" 
            class="class">
        </span>
        <span v-else >
            <em>
            <!-- some 3 lines of code --></em>
        </span>
    </div>
    <div 
        v-if="ok"
        class='classes'>
        <div v-if="ok">
            <div v-if="ok" >
               <!-- some 20 lines of code -->
            </div>
            <div 
                v-else
                class="classes" 
                >
               <!-- some 40 lines of code -->
                <div 
                    class="class">
                    <!-- some 4 lines of code -->
                </div>
            </div>
        </div>
        <div 
            class="option-list" 
            >
            <div
                v-if="ok">
                 <!-- some 30 lines of code -->
            </div>
            <div 
                v-show='condition_ok'
                v-for="(data, i) in list"
                :key="i">
               <!-- some 40 lines of code -->
            </div>
        </div>
     </div>
</div
</template>

所以这是我的模板,它需要近200行代码…..有什么可能的方法可以使它更短,或者我可以从多个位置获取任何模板,并在需要时将其导入?

那就是将组件分成多个片段.

解决方法:

这不仅可能,而且必不可少!

在您的情况下,可以这样进行:

<template>
    <div>
        <div v-if='config.isTag'>
            <CustomComponentOne></CustomComponentOne>
        </div>
        <div v-if="ok"
            class='classes'>
                <CustomComponentTwo></CustomComponentTwo>
            <div class="option-list">
                <div v-if="ok">
                    <CustomComponentThree></CustomComponentThree>
                </div>
                <div v-show='condition_ok'
                    v-for="(data, i) in list"
                    :key="i">
                    <CustomComponentFour></CustomComponentFour>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import CustomComponentOne from '@/components/CustomComponentOne'
    import CustomComponentTwo from '@/components/CustomComponentTwo'
    import CustomComponentThree from '@/components/CustomComponentThree'
    import CustomComponentFour from '@/components/CustomComponentFour'

    export default {
        components: {
            CustomComponentOne,
            CustomComponentTwo,
            CustomComponentThree,
            CustomComponentFour
        }
    }
</script>

<style scoped>

</style>

标签:node-js,vue-js,vue-component,vuejs2,javascript
来源: https://codeday.me/bug/20191108/2006238.html