在工程目录 /src 下创建 component 文件夹,并在 component 文件夹下创建一个 firstcomponent.vue 并写仿照 App.vue 的格式和前面学到的知识写一个组件。
<template>
<div id="firstcomponent">
<h1>I am a title.</h1>
<a> written by {{ author }} </a>
</div>
</template>
<script type="text/javascript">
export default {
data ()
{
return
{ author: "微信公众号 jinkey-love" } } }
</script>
<style> </style>
做完之后如下图所示,不能完全按照官网所给的例子来
然后在 App.vue 使用组件 ( 因为在 index.html 里面定义了<div id="app"></div>所以就以这个组件作为主入口,方便 )
第一步,引入。在 <script></script> 标签内的第一行写
import firstcomponent from './component/firstcomponent.vue'
第二步,注册。在 <script></script> 标签内的 data 代码块后面加上 components: { firstcomponent }。 记得中间加英文逗号!!!
export default {
data ()
{
return { msg: 'Hello Vue!' } },
components: { firstcomponent }
}
第三步,使用。
在 <template></template> 内加上<firstcomponent></firstcomponent>
<template>
<div id="app">
<img src="./assets/logo.png">
<h1>{{ msg }}</h1>
<firstcomponent></firstcomponent>
</div>
</template>
完成后的代码:
这时候看看浏览器上的 http://localhost:8080/ 页面(之前打开过就会自动刷新),如果你没看到效果是因为你没有对 App.vue 和 firstcomponent.vue 进行保存操作,保存后页面会自动刷新