[FE] Hello Vue
2017-08-03 本文已影响154人
何幻
1. 安装Vue
(1)全局安装vue-cli
npm install -g vue-cli
(2)在工程目录中,创建一个基于 webpack 的新项目
vue init webpack my-project
(3)安装依赖,运行
cd my-project
npm install
npm run dev
vue会自动打开浏览器,并访问http://localhost:8080/#/
2. 应用目录
2.1 构建产品代码
npm run build
代码会生成到./dist/
目录下,
dist
├── index.html
└── static
├── css
│ ├── app.3d8d6b1d191ef1f0f5849787035c46a1.css
│ └── app.3d8d6b1d191ef1f0f5849787035c46a1.css.map
└── js
├── app.789525e6da68153e424b.js
├── app.789525e6da68153e424b.js.map
├── manifest.f08ae903444cd4b2344e.js
├── manifest.f08ae903444cd4b2344e.js.map
├── vendor.ae75c6b5bea60f5d8cec.js
└── vendor.ae75c6b5bea60f5d8cec.js.map
2.2 目录结构
index.html
src
├── App.vue
├── assets
│ └── logo.png
├── components
│ └── Hello.vue
├── main.js
└── router
└── index.js
2.3 文件介绍
(1)index.html
index.html
是首页,npm run build
的时候,会自动将css和js注入进去,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>my-project</title>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
(2)src/main.js
src/main.js
应用的入口文件,
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
新建了一个Vue
实例,指定DOM容器元素,路由router,模板以及对App
组件进行局部注册。
(3)App.vue
一个.vue
文件表示一个vue组件,它由<template>
,<script>
和<style>
三部分组成。
本例中的App.vue
组件是整个应用,其中<router-view>
组件是vue内置的,它是一个容器,用来渲染Vue构造函数中router
所指定的内容,即,src/router/index.js
导出的对象。
<template>
<div id="app">

<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'app'
}
</script>
<style>
...
</style>
(4)src/router/index.js
src/router/index.js
导出了一个router,在单页应用中,router由记录url hash值的变更来实现。router模块中,指定了不同的url path
,vue将据此加载不同的组件。其中,Hello
组件由src/components/Hello.vue
导出。
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Hello',
component: Hello
}
]
})
(5)src/components/Hello.vue
src/components/Hello.vue
导出了Hello
组件,vue会自动调用data
函数,来得到<template>
中用到的数据(msg
)。
<template>
<div class="hello">
<h1>{{ msg }}</h1>
...
</div>
</template>
<script>
export default {
name: 'hello',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
...
</style>