vue.js學習之入門實例

以前一直看過vue.js官網api,可是不多實踐,這裏抽出時間謝了個入門級的demo,記錄下一些知識點,防止後續踩坑,牽扯到的的知識點:vue、vue-cli、vue-router、webpack等。css

首先看下實現的效果:html

1

 

源碼下載戳這裏:源碼
vue

一、使用vue-cli腳手架建立項目jquery

vue init webpack tll

備註:使用webpack模板建立名爲tll的項目,這裏會按照提示輸入一些項目基本配置,好比項目名稱、版本號、描述、做者、是否啓用eslint校驗等等,不知道咋填的直接回車便可webpack

二、根據提示啓動項目web

tll項目建立完成後,vue會自動提示幾個命令運行,直接依次執行:vue-router

cd tll
npm i
npm run dev

這樣,一個自動配置好的vue項目便運行起來了,包含熱更新、自動校驗等,固然這些配置在build文件夾下的webpack.base.conf.js裏面,找到loader、preloader加載器,直接註釋掉相應功能也行。好比我寫代碼時,配置了eslint後,稍微有個空格啥的vue-cli

多餘eslint都會報錯致使整個項目沒法運行,這時直接注掉preloader中和eslint相關的便可。npm

三、編寫組件bootstrap

在src的components目錄下,建立home.vue組件,詳細代碼:

<!--首頁組件-->
<template>
    <div class="home">
        <h3>{{msg}}</h3>
    </div>
</template>

<script>
    export default {
        name:"home",
        data(){
            return {
                msg:"這裏是home視圖"
            }
        }
    }
</script>

<style scoped>
    h3{
        background-color: #c5c5c5
    }
</style>

一樣地,建立user.vue組件:

<template>
    <div>
        <h3>{{msg}},獲取到的參數是:{{$route.params.id}}</h3>
    </div>
</template>

<script>
    export default{
        name:"user",
        data(){
            return {
                msg:"這裏是user視圖"
            }
        }
    }
</script>
<style scoped>
    h3{
        background-color:gold
    }
</style>

最後是product.vue組件:

<template>
    <div class="product">
        <h3>{{msg}},獲取到的參數是:{{$route.params.id}}</h3>
    </div>
</template>

<script>
    export default{
        name:"product",
        data(){
            return {
                msg:"這裏是product視圖"
            }
        }
    }
</script>
<style scoped>
    h3{
        background-color:violet
    }
</style>

四、修改app.vue,添加路由

<template>
    <div id="app">
        <nav class="top-menu">
            <ul>
              <!--遍歷li,輸出頂部工具欄-->
               <li v-for="item in menulist">
                  <router-link :to="item.url">{{item.name}}</router-link>
               </li>
            </ul>
        </nav>
        <hr>
        <div>
          <router-view></router-view>
        </div>
    </div>
</template>

<script>
    export default {
        name:"app",
        data:function (){
            return {
                menulist:[
                    {"name":"首頁",url:"/home"},
                    {"name":"用戶",url:"/user/18"},
                    {"name":"產品",url:"/product/20"},
                ]
            }
        }
    }
</script>

<style>
    #app {
        
    }
    .top-menu ul, .top-menu li {
      list-style: none;
    }
    .top-menu {
      overflow: hidden;
    }
    .top-menu li {
      float: left;
      width: 100px;
    }
</style>

五、建立詳細路由配置

在src根目錄下直接新建文件router.js做爲咱們的自定義路由,詳細代碼:

import VueRouter from "vue-router"
import Home from "./components/Home.vue"
import User from "./components/User.vue"
import Product from "./components/Product.vue"

export default new VueRouter({
    routes:[
        {path:"/home",component:Home},
        {path:"/user/:id",component:User},
        {path:"/product/:id",component:Product}
    ]
})

這下便建立了三個導航的匹配路由,最後只要再作一件事便可,那即是讓路由生效:將router掛載到vue實例上。

六、掛載路由組件到vue實例

修改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 VueRouter from "vue-router"    
import router from "./router"

//使用路由組件
Vue.use(VueRouter)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  template: '<App/>',
  components: { App },
  router:router
})

七、一個增刪改查應用

效果以下:

具體實現:

源碼下載戳這裏:源碼

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <script src="http://libs.baidu.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
    <link href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
    <style>
        table thead tr th {
            text-align: center
        }
    </style>
</head>

<body>
    <div style="padding: 20px" id="app">
        <div class="panel panel-primary">
            <div class="panel-heading">用戶管理</div>
            <table class="table table-bordered table-striped text-center">
                <thead>
                    <tr>
                        <th>編號</th>
                        <th>用戶名</th>
                        <th>年齡</th>
                        <th>畢業院校</th>
                        <th>備註</th>
                        <th>操做</th>
                    </tr>
                </thead>
                <tbody>
                    <template v-for="(row,index) in rows">
                        <tr v-if="index>=(curpage-1)*pagesize&&index<curpage*pagesize">
                            <td>{{row.id}}</td>
                            <td>{{row.name}}</td>
                            <td>{{row.age}}</td>
                            <td>{{row.school}}</td>
                            <td>{{row.remark}}</td>
                            <td>
                                <a href="#" v-on:click="Edit(row)">編輯</a>
                                <a href="#" v-on:click="Delete(row.id)">刪除</a>
                            </td>
                        </tr>
                    </template>
                    <tr>
                        <td>
                            &nbsp;
                        </td>
                        <td>
                            <input type="text" class="form-control" v-model="rowtemplate.name">
                        </td>
                        <td>
                            <input type="text" class="form-control" v-model="rowtemplate.age">
                        </td>
                        <td>
                            <select name="" class="form-control" id="" v-model="rowtemplate.school">
                                <option>中山小學</option>
                                <option>復興小學</option>
                                <option>光明小學</option>
                            </select>
                        </td>
                        <td>
                            <input type="text" v-model="rowtemplate.remark" class="form-control">
                        </td>
                        <td>
                            <button type="button" class="btn btn-primary" @click="Save">保存</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        <nav style="float:right">
            <ul class="pagination pagination-lg">
                <template v-for="page in Math.ceil(rows.length/pagesize)">
                    <li @click="PrePage()" id="prepage" v-if="page == 1" class="disabled"><a href="#">上一頁</a></li>
                    <li v-if="page == 1" class="active" @click="NumPage(page,$event)"><a href="#">{{page}}</a></li>
                    <li v-else @click="NumPage(page,$event)"><a href="#">{{page}}</a></li>
                    <li id="nextpage" @click="NextPage()" v-if="page == Math.ceil(rows.length/pagesize)"><a href="#">下一頁</a></li>
                </template>
            </ul>
        </nav>
    </div>
</body>
<script src="http://cdn.bootcss.com/vue/2.1.6/vue.min.js"></script>
<script>
    var data = {
        rows: [{
            id: 1,
            name: '小明',
            age: 18,
            school: '光明小學',
            remark: '三好學生'
        }, {
            id: 2,
            name: '小剛',
            age: 20,
            school: '復興中學',
            remark: '優秀班幹部'
        }, {
            id: 3,
            name: '吉姆格林',
            age: 19,
            school: '光明小學',
            remark: '吉姆作了汽車公司經理'
        }, {
            id: 4,
            name: '李雷',
            age: 25,
            school: '復興中學',
            remark: '不老實的傢伙'
        }, {
            id: 5,
            name: '韓梅梅',
            age: 22,
            school: '光明小學',
            remark: '在一塊兒'
        }, ],
        rowtemplate: {
            id: 0,
            name: '',
            age: '',
            school: '',
            remark: ''
        },
        pagesize: 2,
        curpage: 1
    };
    var vue = new Vue({
        el: "#app",
        data: data,
        methods: {
            PrePage: function (event) {
                jQuery(".pagination .active").prev().trigger("click");
            },
            NextPage: function (event) {
                jQuery(".pagination .active").next().trigger("click");
            },
            NumPage: function (num, event) {
                if (this.curpage == num) {
                    return;
                }
                this.curpage = num;
                jQuery(".pagination li").removeClass("active");
                if (event.target.tagName.toUpperCase() == "LI") {
                    jQuery(event.target).addClass('active');
                } else {
                    jQuery(event.target).parent().addClass('active');
                }
                if (this.curpage == 1) {
                    jQuery('#prepage').addClass('disabled');
                } else {
                    jQuery('#prepage').removeClass('disabled');
                }
                if (this.curpage == Math.ceil(this.rows.length / this.pagesize)) {
                    jQuery('#nextpage').addClass('disabled');
                } else {
                    jQuery('#nextpage').removeClass('disabled');
                }
            },
            Save: function (ev) {
                if (this.rowtemplate.id == 0) {
                    this.rowtemplate.id = this.rows[this.rows.length - 1].id + 1;this.rows.push(this.rowtemplate);
                }
                //還原模板
                this.rowtemplate = {
                    id: 0,
                    name: '',
                    age: '',
                    school: '',
                    remark: ''
                };
            },
            Edit: function (row) {
                // v-model綁定的數據,是雙向的,因此對rowtemplate的修改直接會修改row對象,繼而會修改this.rows數據,因此對最後一行的修改直接會體如今被修改的行上面
                this.rowtemplate = row;
            },
            Delete: function (id) {
                for (var i = 0; i < this.rows.length; i++) {
                    if (id == this.rows[i].id) {
                        this.rows.splice(i, 1);
                        break;
                    }
                }
            }
        }
    });
</script>

</html>
相關文章
相關標籤/搜索