您当前的位置:主页 > 技术探讨 >
vue清坑-组件(二)
时间:2017-10-21 14:07 日记人:arlen.zhou
来玩玩组件
前面讲得基本上都是各种常用组件的数据绑定,下面还得说说的是 Vue 的组件的使用。 在工程目录/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>
duang... 不能按官网文档那样子叫我做就做,我得先试试再告诉你,我做完效果是这样子的,希望观众做完也是这样子。(迷之微笑 )

然后在 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">

<h1>{{ msg }}</h1>
<firstcomponent></firstcomponent>
</div>
</template>
完成后的代码:

这时候看看浏览器上的 http://localhost:8080/
页面(之前打开过就会自动刷新),如果你没看到效果是因为你没有对 App.vue
和 firstcomponent.vue
进行保存操作,保存后页面会自动刷新。
