vue.js学习之入门实例

西安-晁州      2022-02-08     309

关键词:

之前一直看过vue.js官网api,但是很少实践,这里抽出时间谢了个入门级的demo,记录下一些知识点,防止后续踩坑,牵扯到的的知识点:vue、vue-cli、vue-router、webpack等。

首先看下实现的效果:

1

 

源码下载戳这里:源码

1、使用vue-cli脚手架创建项目

vue init webpack tll

备注:使用webpack模板创建名为tll的项目,这里会按照提示输入一些项目基本配置,比如项目名称、版本号、描述、作者、是否启用eslint校验等等,不知道咋填的直接回车即可

2、根据提示启动项目

tll项目创建完成后,vue会自动提示几个命令运行,直接依次执行:

cd tll
npm i
npm run dev

这样,一个自动配置好的vue项目便运行起来了,包含热更新、自动校验等,当然这些配置在build文件夹下的webpack.base.conf.js里面,找到loader、preloader加载器,直接注释掉相应功能也行。比如我写代码时,配置了eslint后,稍微有个空格啥的

多余eslint都会报错导致整个项目无法运行,这时直接注掉preloader中和eslint相关的即可。

3、编写组件

在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>

4、修改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>

5、创建详细路由配置

在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实例上。

6、挂载路由组件到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
})

7、一个增删改查应用

效果如下:

具体实现:

源码下载戳这里:源码

<!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>

 

mybatis学习之环境搭建&入门实例

mybatis:3.2.8数据库:mysql项目结构jar包准备:mybatis-3.2.8.jarmysql-connector-java-5.1.39-bin.jar配置文件1、jdbc.properties配置文件:jdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://127.1.0.1:3306/db_mybatis 查看详情

vue.js学习之——安装

Vue.js的安装方式有三种:1、script引入2、CDN3、NPM前两种不细说,重点讨论第三种——NPM安装Vue.js提供了一个名为Vue-cli的官方命令工具,使用之前先进行如下准备工作:1、安装nvm(NodeVersionManager),简单来说就是一个管理node.js版... 查看详情

06.vue学习之非常实用的计算属性computed实例(代码片段)

<!DOCTYPEhtml><html><head><metacharset="utf-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><title>vue</title><linkrel="stylesheet"href=""><scriptsrc="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script><!--<scripttype="text/... 查看详情

vue.js基础学习之组件

 什么是组件:组件是Vue.js最强大的功能之一。组件可以扩展HTML元素,封装可重用的代码。在较高层面上,组件是自定义的元素,Vue.js的编译器为它添加特殊功能。在有些情况下,组件也可以是原生HTML元素的形式,以is特性... 查看详情

vue.js学习之跨域请求代理与axios传参

vue.js学习之跨域请求代理与axios传参一:跨域请求代理1:打开config/index.jsmodule.exports{dev:{}}在这里面找到proxyTable{},改为这样:proxyTable:{‘/api‘:{target:‘http://121.41.130.58:9090‘,//设置你调用的接口域名和端口号别忘了加httpchangeOrigi... 查看详情

29.vue学习之--键盘事件.键盘修饰符的实例讲解(代码片段)

键盘事件<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><!--<scriptsrc="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>--><scripttype="text/javascript"src="../js/vue.js"></script></head><body><divid="hdcms">&... 查看详情

45.vue学习之--组件之父组件使用scope定义子组件模板样式结构实例讲解(代码片段)

<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><!--<scriptsrc="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>--><scripttype="text/javascript"src="../js/vue.js"></script><!--LatestcompiledandminifiedCSS&JS--><!--<... 查看详情

vue.js基础学习之过滤器

过滤器:filter格式化变量的输出内容,只用于一些简单的在制作的最后一步对内容的输出格式做些调整(如日期格式化,字母大小写,数字再计算等等)例如我们需要将最终的结果字符串以大写方式展示出来,还有将小数转化成... 查看详情

vue.js基础学习之混合mixins

混合以一种灵活的方式为组件提供分布复用功能。混合对象可以包含任意的组件选项。当组件使用了混合对象时,混合对象的所有选项将被“混入”组件自己的选项中。当混合对象与组件包含同名选项时,这些选项将以适当的策... 查看详情

vue学习之四组件系统(代码片段)

vue.js既然是框架,那就不能只是简单的完成数据模板引擎的任务,它还提供了页面布局的功能。本文详细介绍使用vue.js进行页面布局的强大工具,vue.js组件系统。一、Vue.js组件系统每一个新技术的诞生,都是为了解决特定的问题... 查看详情

vue.js源码学习之flag篇(代码片段)

TheProgressiveJavaScriptFramework——vuejs.org起因第一次接触Vue.js是因为要做一个通讯录的外包项目,这个项目要有前台展示和中后台管理,从轮子做起肯定是不明智的选择,所以当时初步定下的是Vue.js+ElementUI的技术栈。项目过程很漫... 查看详情

vue学习之vuex(代码片段)

单向数据流概念Vuex介绍解决问题多个视图依赖于同一状态(菜单导航)来自不同视图的行为需要变更为同意状态(例如:评论弹幕)Vuex应运而生为vue.js开发的状态管理模式组件状态集中管理组件状态改变遵循统一的规则store.js//... 查看详情

vue学习之todolist删除功能(代码片段)

<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0"><metahttp-equiv="X-UA-Compatible"content="ie=edge"><title>vue</title>... 查看详情

27.28.vue学习之--事件修饰符之stop&capture&self&once实例详解(代码片段)

<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><!--<scriptsrc="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>--><scripttype="text/javascript"src="../js/vue.js"></script></head><body><divid="hdcms"><!--默认... 查看详情

elasticsearch学习之入门

1.什么是Elasticsearch  Elasticsearch是一个基于ApcheLucene的开源实时分布式搜索和分析引擎。2.安装  安装Elasticsearch的唯一要求是安装官方新版的java,地址:www.java.com  在elasticsearch.org/download下载最新版本的Elasticsearch。3.运行 ... 查看详情

vue.js学习之如何在better-scroll加载完成后,自动滚动到最底部

 首先我们需要使用scrollTo这个方法:scrollTo(x,y,time,easing)参数:{Number}x横轴坐标(单位px){Number}y纵轴坐标(单位px){Number}time滚动动画执行的时长(单位ms){Object}easing缓动函数,一般不建议修改,如果想修改,参考源码中的e... 查看详情

scala学习之scala快速入门(代码片段)

文章目录Scala的“味道”Overview概述Hello,worldTheScalaREPLTwotypesofvariablesDeclaringvariabletypesControlstructuresif/elsematchexpressionstry/catchforloopsandexpressionswhileanddo/whileClassesScalamethodsTraits 查看详情

elasticsearch学习之入门2

关于Elasticsearch的几个概念:  1)在Elasticsearch中,文档归属于类型type,而类型归属于索引index,为了方便理解,可以把它们与传统关系型数据库做类比:    RelationalDB->DataBases->Tables->Rows->Columns    Elasticsearch->Indices-&g... 查看详情