VUE 2.0 笔记整理

本地使用

elementUI本地引入

element-ui是和vue配套使用的一个框架,官网上给出了在vue-cli下使用的例子,并没有说具体的本地引入,所以自己整理了一下,element-ui引入的时候主要是除了引入css和js之外,还有一个字体库需要下载引入,下面是代码

  • 把vue.js,element.css,element.js下载下来,保存到本地。

  • 把element-ui的两个字体样式拿下来element-icons.woff,element-icons.ttf保存到本地。

  • 最后直接引入,一定要注意路径哦,因为element-ui的字体样式是在element.css里面直接引入的,所以只需要引入vue.js,element.css,element.js,这三个文件即可。

链接地址:
https://unpkg.com/element-ui/lib/theme-chalk/fonts/element-icons.woff

https://unpkg.com/element-ui/lib/theme-chalk/fonts/element-icons.ttf

https://cdn.jsdelivr.net/npm/vue/dist/vue.js

https://unpkg.com/element-ui/lib/theme-chalk/index.css

https://unpkg.com/element-ui/lib/index.js

我的本地目录

<link rel="stylesheet" type="text/css" href="${resource(dir: 'plugins/vue', file: 'index.css')}">
<script type="text/javascript" src="${resource(dir: 'plugins/vue', file: 'vue.min.js')}"></script>
<script type="text/javascript" src="${resource(dir: 'plugins/vue', file: 'index.js')}"></script>

在这里插入图片描述

第一个Vue程序

<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 生产环境版本,优化了尺寸和速度 -->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

实例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
    {{ message }}
<h5 >{{ school.name}} {{school.mobile}}</h5>
    <h5>{{list[1]}}</h5>
</div>
</body>
<script>
    var app = new Vue({
        el: "#app",
        data: {
            message: "hello Vue!",
            school: {name:"小明",mobile:18306846902},
            list: [111,222,333]
        }
    })
</script>
</html>

语法

v-text:属性设置给标签

这里的555不显示,因为v-text会覆盖掉标签内的所有内容

<body>
<div id="app">
   <h5 v-text="message+'!'">555</h5>
   <h5>这里是{{message+'!'}}</h5>
</div>
</body>
<script>
    var app = new Vue({
        el: "#app",
        data: {
            message: "hello Vue!",
        }
    })
</script>

v-html:设置标签的innerHTML

可以解析html文本内容

<body>
<div id="app">
   <h5 v-text="message+'!'">555</h5>
   <h5>这里是{{message+'!'}}</h5>
</div>
</body>
<script>
    var app = new Vue({
        el: "#app",
        data: {
            message: "hello Vue!",
        }
    })
</script>

v-on:元素绑定事件

<body>
<div id="app">
    <input type="button" value="常规" v-on:click="doIt">
    <input type="button" value="简写" @click="doThat">
<input type="text" value="回车绑定事件" @keyup.enter="doThat">
<input type="button" value="双击" @dblclick="doIt">
</div>
</body>
<script>
    var app = new Vue({
        el:"#app",
        methods:{
            doIt:function () {
                alert("v-on");
            },
            doThat:function () {
                alert("@click");
            }
        }
    })
</script>

.stop:阻止冒泡,即不触发外层事件

.prevent:阻止默认事件,即默认打开百度,变成不打开

.capture:添加事件侦听器时使用事件捕获模式,即指定哪个事件先执行

.self:只当事件在该元素本身比如不是子元素,触发时触发回调

.once:事件只触发一次

this关键字在function内部访问data中的数据

<body>
<div id="app">
    <h5 @click="dian">{{message}}</h5>
</div>
</body>
<script>
    var app = new Vue({
        el:"#app",
        data:{
        message:"西蓝花"
        },
        methods:{
            dian:function () {
                this.message += "好吃";
            }
        }
    })
</script>

v-show:显示与隐藏

<body>
<div id="app">
    <img src="../333.jpg" v-show="false">
    <img src="../333.jpg" v-show="isShow">
    <img src="../333.jpg" v-show="age>18">
</div>
</body>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            isShow:true,
            age:16
        }
    })
</script>

v-if 与v-show操作方式一样

原理为v-if直接操作dom树,v-show是加上type=display样式,

切换多的用v-show,切换少的用v-if,因为操作dom比较消耗性能。

v-if v-else v-else-if

v-bind:设置元素属性(src,title,class)

<body>
<div id="app">
    <img src="../333.jpg" v-show="false">
    <img src="../333.jpg" v-show="isShow">
    <img src="../333.jpg" v-show="age>18">
</div>
</body>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            isShow:true,
            age:16
        }
    })
</script>

v-for:根据数据生成列表结构

数组长度的更新会响应式的同步到页面上

<body>
<div id="app">
    <ul>
        <li v-for="(it,index) in message" :key="">
            {{index+1}}开始{{it}}
        </li>
    </ul>
</div>
</body>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            message:[1,2,3,4,5,6]
        }
    })
</script>

v-model:获取和设置表单元素的值(双向数据绑定)

<body>
<div id="app">
    <input type="text"  v-model="message">
    <h3>{{message}}</h3>
</div>
</body>
<script>
    var app = new Vue({
        el:"#app",
        data:{
            message:"双向绑定数据"
        }
    })
</script>

v-clock解决差值表达式闪烁问题

<style>
    [v-cloak]{
        display:none;
    }
</style>


<p v-cloak>{{city}}</p>

计算属性 Computed

computed: {
    NewCoefficient() {
        return this.formData.coefficient;
    },
    NewAmount() {
        return this.formData.amount;
    }
},
watch: {
    NewCoefficient(val, oldval){
        if (this.formData.amount != null){
            this.formData.reqManhour = this.formData.amount/this.formData.coefficient*8
        }
    },
    NewAmount(){
        if (this.formData.coefficient != null){
            this.formData.reqManhour = this.formData.amount/this.formData.coefficient*8
        }
    }
},

监视watch

 watch:{
	firstName:function(newvalue,oldValue){
	console.log(newvalue);
	}
 }

记事本小应用

<body>
    <!--主体区域-->
        <section id="todoapp">
            <!--输入框-->
            <header class="header">
                <h1>记事本</h1>
                <input  v-model="inputValue" autofocus="autofocus" autocomplete="off" placeholder="请输入任务" class="new-todo"
                @keyup.enter="add"/>
            </header>
            <!--列表区域-->
            <section class="main">
                <ul class="todo-list">
                    <li class="todo" v-for="(it,index) in li">
                        <div class="view">
                           <span>{{index+1}}</span>
                            <label>{{it}}</label>
                            <button class="destroy" @click="destroy(index)">删除</button>
                        </div>
                    </li>
                </ul>
            </section>
            <span v-if="li.length!=0">共{{li.length}}条</span><br>
            <button @click="clear" v-if="li.length!=0">clear</button>
        </section>
</body>
    <script>
    var app = new Vue({
        el:"#todoapp",
        data:{
            li:["哈哈","呵呵","哇"],
            inputValue:""
        },
        methods:{
            destroy:function (index) {
                this.li.splice(index,1);
            },
            add:function () {
                // var ll = document.getElementById("s").value
                this.li.push(this.inputValue)
            },
            clear:function () {
                this.li.splice(0,this.li.length);
            }
        }
    })
</script>

组件

自定义组件:

<body>
    <!--主体区域-->
        <section id="todoapp">
            <!--输入框-->
            <header class="header">
                <h1>记事本</h1>
                <input  v-model="inputValue" autofocus="autofocus" autocomplete="off" placeholder="请输入任务" class="new-todo"
                @keyup.enter="add"/>
            </header>
            <!--列表区域-->
            <section class="main">
                <ul class="todo-list">
                    <li class="todo" v-for="(it,index) in li">
                        <div class="view">
                           <span>{{index+1}}</span>
                            <label>{{it}}</label>
                            <button class="destroy" @click="destroy(index)">删除</button>
                        </div>
                    </li>
                </ul>
            </section>
            <span v-if="li.length!=0">共{{li.length}}条</span><br>
            <button @click="clear" v-if="li.length!=0">clear</button>
        </section>
</body>
    <script>
    var app = new Vue({
        el:"#todoapp",
        data:{
            li:["哈哈","呵呵","哇"],
            inputValue:""
        },
        methods:{
            destroy:function (index) {
                this.li.splice(index,1);
            },
            add:function () {
                // var ll = document.getElementById("s").value
                this.li.push(this.inputValue)
            },
            clear:function () {
                this.li.splice(0,this.li.length);
            }
        }
    })
</script>

钩子函数

Mounted

  mounted: function(){
      this.$axios
        .get("/api/tree")
        .then(res => {
          this.data2 = res.data.data
    })
  }
};

beforeRouteEnter,beforeRouteLeave

 beforeRouteEnter (to, from, next) {
    console.log("准备进入主页",to,from)
    next()
  },
  beforeRouteLeave (to, from, next) {
    console.log("准备离开主页",to,from)
    next()
  }

vue+axios结合

vue项目中

cnpm install axios --save

npm install qs --save

Main.js 中:

import axios from 'axios'
Vue.prototype.$axios = axios
import qs from 'qs'
Vue.prototype.$qs = qs

qs主要有两个方法 :

| 方法一:将对象序列化,多个对象之间用&拼接(拼接是由底层处理,无需手动操作)

qs.stringify()  转换成查询字符串
let comments = {content: this.inputValue}
let comValue = qs.stringify(comments)

方法二:将序列化的内容拆分成一个个单一的对象

qs.parse() 转换成json对象
let comValue = qs.parse(comments)

Axios跨域问题:
/config/index.js中

module.exports = {
  dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target: 'http://localhost:8300/', // 需要跨域请求的地址或者IP
        changeOrigin: true, //  表示是否跨域
        pathRewrite: {
          '^/api': '' // 表示需要rewrite重写的
        }
      }
    },

具体使用:

methods: {
    submitForm(formName) {
      console.log(this.ruleForm)
      this.$axios
        .post("/api/login", this.ruleForm,{ 'Content-Type': 'application/json'})
        .then(res=>{
          console.log(res)
        });
    },

js中

Axios网络请求库

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
使用方式:
axios.get(地址?key=value&key2=value).
.then(response => {
        this.info = response.data.bpi
                    })
     .catch(error => {
        console.log(error)
        this.errored = true
                  })
      .finally(() => this.loading = false)
          }
axios.post(地址,{key=value,key2=value},{ 'Content-Type': 'application/json'}).
then(
function(response)){},
function(err){})


vue中class样式使用

1.数组:
<h1 :class="['red','thin']"></h1>
2.数组中使用三元素表达式
<h1 :class="['red','thin',isactive?'active':'']"></h1>
3.数组中嵌套对象
<h1 :class="['red','thin',{'active':isactive}]"></h1>
4.直接使用对象 
<h1 :class="{red:true,italic:true,active:true,thin:true}"></h1>

vue过滤器进行文本格式化

过滤器只能在 v-bind {{}} 差值表达式中使用

1.数组:
<h1 :class="['red','thin']"></h1>
2.数组中使用三元素表达式
<h1 :class="['red','thin',isactive?'active':'']"></h1>
3.数组中嵌套对象
<h1 :class="['red','thin',{'active':isactive}]"></h1>
4.直接使用对象 
<h1 :class="{red:true,italic:true,active:true,thin:true}"></h1>

slot插槽

<div id="app">
   <todo>
       <todo-title slot="todo-title"></todo-title>
       <todo-items slot="todo-items"></todo-items>
   </todo>
</div>
</body>
<script>
    Vue.component("todo",{
        template:"<div>\
                    <slot name = 'todo-title'></slot>\
                    <ul>\
                        <slot name='todo-items'></slot>\
                    </ul>\
                  </div>\
                    "
    })
    Vue.component("todo-title",{
        template:"<div>标题</div>"
    })
    Vue.component("todo-items",{
        template:"<li>内容</li>"
    })
    var vm= new Vue({
        el:"#app",
    })
</script>

Vue子父组件传值

父组件向子组件传值

parent:

<parent>
    <child :test="test"></child>
</parent>

import child from './child ';
components: {child },

data(){
   return {
        test: "this is parent message"
          }
     }
child:

<div>
    <p>{{message}}</p>
</div>

export default {
    props: ["test","www"],
or
props: {
    message: {
    type: String,                 //可指定接收类型,如:Array.
    default:"this is default"     //可设置默认值
      }
}

props: {
message: {
type: Array,
default: ['foo','bar','baz']   //默认值
}
}

注意:parent中的子组件标签中传入的是 :message, (v-bind:"message"),如果传入的是message="msg",那么子组件接收到的是"msg"这个字符串,因为message没有绑定值。

子组件向父组件传值

子组件向父组件传值
由于在vue中子组件不能更改父组件中的内容,所以可以通过子组件触发事件来传值给父组件。

child:

<template>
    <button v-on:click ='setValue'>setValue</button>
</template>

data(){
   return {
         value: "sendValue"
           }
       },
methods:{
     setValue:function(){
     this.$emit('getdata',this.value); //this.value为向父组件传递的数据
       }
}

parent:
<div id="app">
    <child @getdata="receive" ></child> //自动监听由子组件"注册"的 'getdata'事件,然后调用receive方法来更改数据
</div>

data(){
  return{
     value:"default"
        }
 },
methods: {
    receive:function(val) {
    this.value = val;
          }
}

非父子组件之间的通讯

有时候两个非父子关系组件也需要通信 。在简单的场景下,可以使用一个空的 Vue 实例作为中央事件总线,类似于一个“中转站”,进行发送和接收数据。
<template>
    <div>
        <Card :bordered="false" dis-hover class="ivu-mt">
            <table-form @on-submit="getData" @on-reset="getData" />
            <table-list ref="table" />
        </Card>
    </div>
</template>
<script>
    import tableForm from './table-form';
    import tableList from './table-list';

    export default {
        name: 'list-table-list',
        components: { tableForm, tableList },
        data () {
            return {

            }
        },
        methods: {
            getData (data) {
                this.$refs.table.current = 1
                this.$refs.table.selectedData = []
                this.$refs.table.getData(data);
            }
        },
        mounted () {
            this.getData();
        }
    }
</script>

在数据简单的情况下可以使用中转或者父组件传值给子组件的方法进行传值,在数据比较多而杂的情况下,应该考虑使用专门的状态管理模式 Vuex插件来实现组件间的通讯.

WebPack

安装:npm install webpack webpack-cli -g

检查安装:webpack -v

webpack-cli -v

创建 webpack.config.js 配置文件

entry:入口文件,指定 WebPack 用哪个文件作为项目的入口
output:输出,指定 WebPack 把处理完成的文件放置到指定路径
module:模块,用于处理各种类型的文件
plugins:插件,如:热更新、代码重用等
resolve:设置路径指向
watch:监听,用于设置文件改动后直接打包

直接运行 webpack 命令打包

vue-cli

安装 vue-cli

  • 安装 Node.js

请自行前往 http://nodejs.cn/download 官网下载安装,此处不再赘述

  • 安装 Node.js 淘宝镜像加速器(cnpm)

或使用如下语句解决 npm 速度慢的问题npminstall

npm install cnpm -g–registry=https://registry.npm.taobao.org

  • 安装 vue-cli

npm install vue-cli -g

  • 测试是否安装成功

查看可以基于哪些模板创建 vue 应用程序,通常我们选择 webpack

vue list

在这里插入图片描述

创建一个基于webpack模板的vue应用程序

这里的 myvue 是项目名称,可以根据自己的需求起名

vue init webpack myvue

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZvQXhUBZ-1603197734349)(RackMultipart20201020-4-o11xf9_html_16c5f4f23d438acf.png)]

** 说明**

  • Project name:项目名称,默认 回车 即可
  • Project description:项目描述,默认 回车 即可
  • Author:项目作者,默认 回车 即可
  • Install vue-router:是否安装 vue-router,选择 n 不安装(后期需要再手动添加)
  • Use ESLint to lint your code:是否使用 ESLint 做代码检查,选择 n 不安装(后期需要再手动添加)
  • Set up unit tests:单元测试相关,选择 n 不安装(后期需要再手动添加)
  • Setup e2e tests with Nightwatch:单元测试相关,选择 n 不安装(后期需要再手动添加)
  • Should we run npm install for you after the project has been created:创建完成后直接初始化,选择 n,我们手动执行

** 初始化并运行**

cd myvue

npm install --registry=https://registry.npm.taobao.org

(推荐使用上边这个这个速度快也可以用后边这个,不要用cnpm会有一些bug)

npminstall

npm run dev

安装并运行成功后在浏览器输入:http://localhost:8080

VueRouter

安装:在项目内部 npm install vue-router --save-dev

普通路由

添加新的跳转,即实现点击左侧菜单右侧进行跳转

在router下的index.js中
export default new Router({
  routes: [
    {
      path: '/',
      component: Index
    },
    {
      path: '/Home',
      component: Home
    },
    {
      path: '/Config',
      component: Config
    },
    {
      path: '/Application',
      component: Application
    }
  ]

import与之对应并在components下建立对应页面

import Home from '@/components/Home'
import Config from '@/components/Config'
import Application from '@/components/Application'
import Index from '@/components/Index'

在对应的标签中添加router属性

  <div class="children">
    <router-link to='/index1'>index1</router-link>
    <router-link to='/index2'>index2</router-link>
  </div>
    <div >
        <router-view></router-view>
    </div>

嵌套路由

  1. 创建组件页面
  2. 注册路由 src/router/index.js,** 红色部分为嵌套的路由**
export default new Router({
  routes: [
    {
      path: '/',
      component: application
    },
    {
      path: '/index1',
      component: index1,
      children:[{
        path:'/index1/news',  注意这里的路径需要写上父路径
        component: news
      },{
        path:'nnn',
        component: nnn     也可以不写/ 这样的简写
      }
    ]
    },
    {
      path: '/index2',
      component: index2
    },
  ]
})
  1. 页面中使用:在要父路由的页面中引用
	<router-link to="/index1/nnn">nnn</router-link>
    <router-link to="/index1/news">news</router-link>
    <div> 	<router-view></router-view>	   </div>

路由缓存

就是切换路由以后由于点击切换时候当前路由会死亡,切换回来时候会新建路由所以,内容不保留,因此需要路由缓存。

 <div>
      <keep-alive>(加这个标签就可以缓存路由)
        <router-view></router-view>
      </keep-alive>
    </div>

路由传参

 children: [{
           path:'/index1/news/msg/:id',
           component:msg ,
        }]
 <router-link to="'/index1/news/msg/${user.id}'">sss</router-link>
或者
 children: [{
           path:'/index1/news/msg',
           component:msg ,
        }]
<router-link to="'/index1/news/msg?id=${user.id}'">sss</router-link>

子页面获取传递过来的参数

路由页面跳转 $router.push

push是直接

  <button @click="pushShow()">push查看</button>
  <button @click="pushShow()">push查看</button>
  <button @click="$router.back()">回退</button>
    methods: {
      pushShow(){
          this.$router.push(‘这里填路由中设置的路径’)
      },
       pushShow(){
          this.$router.replace(‘这里填路由中设置的路径’)
      },
  },

1.this.$router.push()

描述:跳转到不同的url,但这个方法会向history栈添加一个记录,点击回退会返回到上一个页面。

2.this.$router.replace()

描述:同样是跳转到指定的url,但是这个方法不会向history里面添加新的记录,点击返回,会跳转到上上一个页面。上一个记录是不存在的。

3.this.$router.go(n)

相对于当前页面向前或向后跳转多少个页面,类似 window.history.go(n)。n可为正数可为负数。正数返回上一个页面

Vuex

对vue应用中多个组件的共享状态进行集中式的管理(读/写)

下载:npm install vuex --save

src下新建 store.js模板:

// vuex的核心管理对象

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
//状态对象
const state = {}
//包含多个更新state函数的对象
const mutations = {}
//包含多个对应事件回调函数的对象
const actions = {}
//包含多个getter计算属性函数的对象
const getters = {}


export default new Vuex.Store({

    state,//状态对象

    mutations,//包含多个更新state函数的对象

    actions, //包含多个对应事件回调函数的对象

    getters //包含多个getter计算属性函数的对象

})

##main.js中引入 js

import store from './store'

new Vue({
  el: '#app',
  router,
  store,//相当于store: store,注册后子组件中可以使用this.$store访问
  components: { App },
  template: '<App/>'
})

state要管理的对象放在state中

//状态对象
const state = {
count: 3,
name: 张三
}

页面中调用:

 <h1>{{$store.state.count}}  </h1>

Vuex 的刷新页面丢失问题处理

有些小伙伴可能发现了,vuex在页面刷新后,store中的状态将被重新初始化,赋值的数据丢失,针对这个问题怎么处理呢? —我们可以这样处理,在页面刷新或离开之前将store中的数据保存到sessionStorage 或 localStorage中,在页面重新加载后再将数据取出,通过vuex的$store.replaceState 将数据替换到store中,上代码

app.vue:

created() {
    var store = require("store");

    //在页面加载时读取sessionStorage里的状态信息
    if (sessionStorage.getItem("storedata")) {
      this.$store.replaceState(
        Object.assign(
          {},
          this.$store.state,
          JSON.parse(sessionStorage.getItem("storedata"))
        )
      );
    }
    //在页面刷新时将vuex里的信息保存到sessionStorage里
    window.addEventListener("beforeunload", () => {
      sessionStorage.setItem("storedata", JSON.stringify(this.$store.state));
    });
    // 兼容iphone手机
    window.addEventListener("pagehide", () => {
      sessionStorage.setItem("storedata", JSON.stringify(this.$store.state));

页面中简化写法

Import以后页面中HTMl中可直接写state 使用也是…格式

import {mapActions,mapGetters,mapState} from 'vuex'

 computed: {
    ...mapState(['count']),
    ...mapGetters(['evenOrOdd'])
  },

Echars

  • 安装:cnpm install echarts --save
  • main.js中,将echarts导入并注册到vue的属性中
import echarts from 'echarts';
Vue.prototype.$echarts = echarts;
  1. 第一个实例
<div id="echarts" style="width: 600px;height:400px;"></div>
<script>
export default {
  mounted(){
    this.init();
  },
  methods:{
    init(){
      // 基于准备好的dom,初始化echarts实例
        var myChart = this.$echarts.init(document.getElementById('echarts'));
        // 指定图表的配置项和数据
        var option = {
            title: {
                text: 'ECharts 入门示例'
            },
            tooltip: {},
            legend: {
                data:['销量']
            },
            xAxis: {
                data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
            },
            yAxis: {},
            series: [{
                name: '销量',
                type: 'bar',
                data: [5, 20, 36, 10, 10, 20]
            }]
        };
        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
    }
  }
};
</script>

vue中访问静态资源两种方式

<template>
   <el-carousel :interval="5000" arrow="always">
    <el-carousel-item v-for="item in src" :key="item">
      <el-image :src="item"></el-image>
    </el-carousel-item>
  </el-carousel>
</template>

<script>
export default {
  data () {
    return {
      src: [require('../assets/logo.png'),  (这是访问assets中的图片)
            '/static/222.jpg'] (这是访问static中的图片)
    }
  }
}
</script>

项目打包

  • /build/webpack.prod.conf.js下添加
devtool: config.build.productionSourceMap ? config.build.devtool : false,
  output: {
    path: config.build.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
    publicPath: '/first_vue/'   (就这一句,引号内为你项目的名字)
  },
  • build文件夹下的utils.js的publicPath:'…/…/'
devtool: config.build.productionSourceMap ? config.build.devtool : false,
  output: {
    path: config.build.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
    publicPath: '/first_vue/'   (就这一句,引号内为你项目的名字)
  },

命令:npm run build 打包后出现一个dist文件,将dist文件名字修改为上边第一步定义的名字,放到tomcat下的webapps下启动tomcat访问即可

常用方法

json字符串转对象:Json.parse(字符串)

Json对象转字符串:Json.stringify(对象)

sessionStorage中取值:sessionStorage.getItem(‘key’)

sessionStorage中存值:sessionStorage.setItem(‘key’,‘value’)

url中去掉#方法和路由跳转相同路径报错解决办法

  Vue.use(Router)

  export default new Router({
  mode:'history',  添加这句就行了

正则表达式总结

只能输入数字且只有两位小数

{ pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/, message: '请输入合法的税率(%),最多两位小数', trigger: 'change' },

只能输入0-100的整数

{
    pattern: /(^[1-9][0-9]$)|(^100&)|(^[0-9]$|100)$/,
    message: '只能输入0-100的整数',
    trigger: 'change'
},

只能输入数字

{
    pattern: /^\d+$|^\d+[.]?\d+$/,
    message: '请输入合法的项目金额,只能输入数字',
    trigger: 'change'
}`

邮箱校验

{ 
pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, 
message: '请输入有效的邮箱地址', 
trigger: 'blur'
 }

电话校验

{
    pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
    message: '请输入合法的联系方式',
    trigger: 'change'
}

税号

{
    pattern: /[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}/,
    message: '请输入有效税号',
    trigger: 'blur'
}

邮编校验

zipcode: [
    {required: true, message: '请输入邮编', trigger: 'blur'},
    {
    pattern: /^[0-9]{6}$/,
	message: '请输入有效的邮编',
	trigger: 'change'
    }
],

不允许有空格

{
    pattern: /^[^\s]*$/,
    message: '不允许有空格',
    trigger: 'blur'
},

常见问题

vue 实现textarea展示时自动换行

利用 v-html 展示 str.replace(/\n|\r\n/g, ‘
’) 数据 完美解决
利用 v-html 展示 **str.replace(/\n|\r\n/g, ‘&lt;br&gt;’) **数据 完美解决

直接传row时候出现问题解决方案

handleEdit(row) {
    this.editData = Object.assign({},row)
    this.$refs.mef.show = true;
},

iView upload组件action问题问题

import util from '@/libs/util';
uploadHeader:{'X-Token':util.cookies.get('token')},
<Upload :action="$store.state.upload"  :headers="uploadHeader"

设置异步延迟方法,多少秒后执行

 setTimeout(() => {
          内容
      }, 1000);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sparrow6902

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值