Vue.js传递道具动态更改组件类

Yor*_*hev 1 vue.js vue-component vuejs2

我正在努力学习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',
  }

);
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

这是在检查员的输出中.你可以看到道具[类型]没有改变.

<div role="alert" class="alert alert-{{ type }}'"><b>Slow down.</b> You might crash.</div>
Run Code Online (Sandbox Code Playgroud)

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

acd*_*ior 5

在vue 2中,您不能再在属性中使用插值.现在,您有几种可能的类和样式绑定语法.在您的具体情况下,您可以使用:

<div class="alert" :class="'alert-' + type" role="alert">
Run Code Online (Sandbox Code Playgroud)

演示如下.

new Vue({
  el: '#app',
  data: {
    type: 'warning'
  }
})
Run Code Online (Sandbox Code Playgroud)
.alert { background: yellow; }
.alert-warning { color: red }
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <div class="alert" :class="'alert-' + type" role="alert"> Warning! </div>
</div>
Run Code Online (Sandbox Code Playgroud)