【问题标题】:Cloning a single file Vue component (template and functionality)克隆单个文件 Vue 组件(模板和功能)
【发布时间】:2018-05-05 13:08:21
【问题描述】:

我目前有一个 Vue 组件,我在我的应用程序的一部分中使用它。我想在我的应用程序的另一部分使用相同的组件;但是,我想对 CSS 做一些小的改动(改变背景颜色等)。

简单但重复的方法是简单地将组件复制并粘贴到一个新的 .vue 文件中,并进行相应的 CSS 更改;但是,有没有更好的方法来实现这种效果?

理想情况下,我希望能够创建一个新的 Vue 组件,它可以导入整个模板以及方法、道具等。我已经研究过使用 extends;但是,它不会导入 Vue 模板 - 只是功能。

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    您可以将 css 类名作为 props 传递:

    Vue.component('my-component', {
      template: '#my-component',
      props: ['styled']
    })
    
    new Vue({
      el: '#app',
    })
    body {
      font-family: "Montserrat"
    }
    
    .card {
      border-radius: 8px;
      margin: 20px;
      padding: 30px 40px;
    }
    
    .first-component {
      background-color: #FFBF88;
      font-size: 16px;
      font-weight: bold;
    }
    .second-component {
      background-color: #C4E0F1;
      font-size: 12px;
      text-align: right;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
    
    <div id="app">
      <my-component styled="first-component"></my-component>
      <my-component styled="second-component"></my-component>
    </div>
    
    
    
    <template id="my-component">
      <div class="card" :class="styled">
          I'm the same component
      </div>
    </template>

    【讨论】:

    • 我支持这种方法。如果它实际上只是装饰性的 CSS 是要走的路。您甚至可以将其他样式拆分为单独的样式标签以使其分开。 &lt;style scoped&gt; /* styles for one */ &lt;/style&gt; &lt;style scoped&gt; /* overrides for two */ &lt;/style&gt;.
    猜你喜欢
    • 2021-08-25
    • 1970-01-01
    • 2017-10-10
    • 1970-01-01
    • 2016-05-25
    • 2016-12-29
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多