为了理解这一点,Hello组件应该长这样:
#src/components/Hello.vue
<template>
<div class="hello">
<p>Welcome to TutsPlus {{ name }}</p>
<hr>
<button @click="changeName">Change Display Name</button>
<!-- Detail component is outputted using the name it was registered with -->
<Detail/>
</div>
</template>
<script>
// Importation of Detail component is done
import Detail from './Detail'
export default {
name: 'HelloWorld',
data () {
return {
name: 'Henry'
}
},
methods: {
changeName () {
this.name = 'Mark'
}
},
/**
* Detail component gets registered locally.
* This component can only be used inside the Hello component
* The value passed is the name of the component
*/
components: {
Detail
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
刷新页面以查看新页面。
范围组件样式
Vue.js允许你为组件提供全局和本地样式。是什么意思呢?在某些情况下,你希望组件中的某些元素与另一个组件中的对应元素的样式不同。Vue.js能够帮助你。
一个很好的例子是你刚刚建立的小应用程序。App.vue中的样式是全局的; 这怎么可能? 打开你的App.vue,风格部分看起来像这样。
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
这与Detail.vue不同,看起来像这样。
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
将 scoped 添加到样式标签是造成这个差别的原因。 尝试通过删除 scoped 来编辑一种组件样式,你会看到这是如何运作的。
结论
虽然这个文章有点长,但是我相信你会喜欢它。
现在你知道如何有效地使用组件,并且了解如何在现有应用程序中构建组件。在使用vue-cli时,你还可以在本地和全局范围内创建和使用组件。当你想为一个组件使用特定的风格时,你已经看到了如何使用scoped来做到这一点。
你现在可以继续构建使用组件的复杂Vue.js应用程序。了解Vue.js允许你重用代码,你的页眉,页脚,登录面板和搜索栏可以用作组件。
