【问题标题】:Vue.js pass props to dynamicly change component classVue.js 通过 props 动态改变组件类
【发布时间】:2018-08-24 11:53:35
【问题描述】:

我正在尝试学习 Vue 并遇到了这个问题。

Vue.component('alert', {
  props: ['type', 'bold', 'msg'], template: '<div class="alert alert-{{ type }}" role="alert"><b>{{ bold }}</b> {{ msg }}</div>'
});

var componentProps=new Vue( {
    el: '#app',
  }

);
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div id="app" class="container">
  <alert type="info" bold="Greetings." msg="This is some information."></alert>
  <alert type="warning" bold="Slow down." msg="You might crash."></alert>
  <alert type="danger" bold="Oh no!" msg="The program just crashed!"></alert>
  <alert type="success" bold="Rock Out" msg="with your Props out!"></alert>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue"></script>

这是在检查器的输出中。你可以看到 props[type] 在那里没有改变。

<div role="alert" class="alert alert-{{ type }}'"><b>Slow down.</b> You might crash.</div>

codepen 链接 => https://codepen.io/dakata911/pen/XEKbyq?editors=1010

【问题讨论】:

    标签: vue.js vuejs2 vue-component


    【解决方案1】:

    在 vue 2 中你 can't use interpolations in attributes anymore。你现在有several possible syntaxes for class and style bindings。在您的具体情况下,您可以使用:

    <div class="alert" :class="'alert-' + type" role="alert">
    

    下面的演示。

    new Vue({
      el: '#app',
      data: {
        type: 'warning'
      }
    })
    .alert { background: yellow; }
    .alert-warning { color: red }
    <script src="https://unpkg.com/vue"></script>
    
    <div id="app">
      <div class="alert" :class="'alert-' + type" role="alert"> Warning! </div>
    </div>

    【讨论】:

      【解决方案2】:

      关于属性插值不起作用,可以使用:绑定

      :class="type"

      :class="[ type, other, ... ]"

      :class="{ 'someClass': true, 'other-class': false, 'another': method() }"

      你可以在同一个元素/标签上同时拥有:class="..." 属性和class="normal class attribute"

      【讨论】:

        猜你喜欢
        • 2019-06-08
        • 2020-06-29
        • 2018-04-14
        • 1970-01-01
        • 2015-09-25
        • 2020-11-03
        • 2016-12-23
        • 2019-07-14
        • 2021-03-02
        相关资源
        最近更新 更多