解析Vue.js中的组件

2020-06-16 05:41:00易采站长站整理

<display-name/>
</div>
</template>
<script>
export default {
}
</script>
<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>

打开服务器,打开http:// localhost:8080。 点击按钮,名称应该改变。

我们来看看如何在本地使用一个组件。

在组件目录中创建一个名为Detail.vue的文件。 这个组件不会做任何特殊的事情 – 它将被用在Hello组件中。

使你的Detail.vue文件就像这样。


#src/components/Detail.vue
<template>
<div class="hello">
<p>This component is imported locally.</p>
</div>
</template>
<script>
export default {
name: '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>

要在Hello组件中使用它,可以像导入Hello组件一样将其导入。 接下来,把它注册,但这次你不需要使用Vue.component()构造函数。

你可以使用导出内的组件对象进行注册。将用作元素标记的组件的名称必须作为值传递给对象。 完成后,你现在可以使用元素标记来输出组件。

为了理解这一点,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;