假如我们定义了一个这样的组件:
function Article(title, count) {
this.title = title;
this.count = count;
}
Vue.component("my-component", {
props: {
article: Article
},
template: `
<div>
<h2>{{ article.title }}</h2>
<p>Count: {{ article.count }}</p>
</div>
`
});为了给我们的组件定制一个主题,我们可能需要像这样添加一个特殊的 class 名:
<my-component v-bind:article="article" class="date-picker-theme-dark"></my-component>
在这种情况下,我们定义了两个不同的 class 的值:
(1)article_item 这是在组件的模板内设置好的 class。
(2)article_item_theme 这是从组件的父级传入的 class。
对于绝大多数属性来说,从外部提供给组件的值会替换掉组件内部设置好的值。所以如果传入 type="text" 就会替换掉 type="date" 并把它破坏!庆幸的是,class 和 style 属性会稍微智能一些,即两边的值会被合并起来,从而得到最终的值:class="article_item article_item_theme"。
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue</title>
<!-- 使用 CDN 引入 Vue 库 -->
<!-- <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> -->
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.9/vue.js"></script>
</head>
<body>
<div id="app">
<my-component v-bind:article="article"></my-component>
</div>
<script type="text/javascript">
function Article(title, count) {
this.title = title;
this.count = count;
}
Vue.component("my-component", {
props: {
article: Article
},
template: `
<div>
<h2>{{ article.title }}</h2>
<p>Count: {{ article.count }}</p>
</div>
`
});
var app = new Vue({
el: "#app",
data: {
article: new Article("Hello Vue.js", 1024)
}
});
</script>
</body>
</html>运行效果如下图:
