天天看点

一个初学者的vue2.0练习程序

本文主要参考了Vue2.0 新手完全填坑攻略—从环境搭建到发布——Jinkey 原创。跟其主要区别在于本文使用了element ui和其提供的element starter,同时本文不涉及vue-resource(如果有下一篇会展示如何使用vue-resource)。本文会展示如何构建一个简单的页面,如何构建一个component,同时会展示如何简单使用vue-router。作为初学者,感觉vue的大体思想类似于面向对象,将数据和操作放在一起同时进行封装。一个大的项目由多个小的封装好的组件组合而成。

1. 安装nodejs。

2. 安装webpack: npm install -g webpack。直接这样进行安装有时会比较慢。建议使用淘宝npm源,但是不建议使用cnpm。因为曾经使用cnpm出过奇怪的包依赖问题。

3. 安装vue-cli: npm install -g vue-cli

4. 下载element starter: git clone https://github.com/ElementUI/element-starter.git

5. 进入element-starter目录,打开命令窗口输入:npm install。待安装完成后执行npm run dev。打开浏览器访问localhost:8010应该可以看到页面。

6. 首先创建第一个component(命名为firstCom.vue放在src\components文件夹中):

<template>
  <div id="firstCom">
    <h1>I am a component.</h1>
    <a> written by {{ author }} </a>
  </div>
</template>

<script type="text/javascript">
    export default {
        data () {
            return {
            author: "Jinkey"
            }
        }
    }
</script>
           
  1. 这时如果在app.vue中加入下面的代码,应该可以看到页面上出现了firstCom中的内容。
<template>
    <div id="app">
        ...
        <firstCom></firstCom>
        ...
    </div>
</template>
<script>
    import firstCom from './components/firstCom.vue'
</script>
           
  1. 为了演示vue-router暂时去掉上面代码中的
  2. 安装vue-router: npm install vue-router –save
  3. 在app.vue中加入:
<template>
    <div id="app">
        ...
        <a href="/first">click me</a>
        <router-view class="view"></router-view>
        ...
    </div>
</template>
           
  1. 在main.js中加入:
import VueRouter from 'vue-router'
import firstCom from './components/firstCom.vue'
...
Vue.use(VueRouter)
const router = new VueRouter({
  mode: 'history',
  base: __dirname,
  routes: [
    {
      path: '/first',
      component: firstCom
    }
  ]
})
           
  1. 改写main.js:
new Vue({
  // insert this line
  router: router,
  el: '#app',
  render: h => h(App)
})
           

此时,点击页面上的链接“click me”应该可以看到firstCom中定义的内容。

这个过程是我回忆着写的,如果有问题请告知。源码可以在github看到。