vue实用技巧总结

总结一些新手可能会迷惑可是项目中经常使用的小技巧html

.native

给组件绑定原生事件vue

对于通常的html元素,绑定自定义事件使用v-on便可,可是在某个组件的根元素上监听一个原生事件,好比:web

<my-component v-on:click="doTheThing"></my-component>

咱们会发现这样是不起做用的,可使用 .native 修饰vue-router

<my-component v-on:click.native="doTheThing"></my-component>

自定义组件上的v-model

你们知道v-model 是用来进行数据双向绑定,经常使用于表单控件元素上数据的自动更新。
如:vue-cli

<input v-model="something">

其实它不过是下面示例的简写npm

<input v-bind:value="something" v-on:input="something = $event.target.value">

因此在自定义组件上也可使用v-modelapp

<custom-input v-model="something"></custom-input>

至关于下面示例的简写ui

<custom-input v-bind:value="something" v-on:input="something = arguments[0]"></custom-input>

在组件内部,经过this.$emit('input', value)能够改变something的值this

使用require.ensure按需加载组件

使用vue-cli构建项目,默认状况下,路由文件(/router/index.js)使用import引入vue组件:spa

import Vue from 'vue'
import Router from 'vue-router'
import Index from '@/components/Index'

执行npm run build以后,webpage会打包成一个总体的js文件:app.[contenthash].js,这个文件的体积是很庞大的,几兆甚至几十兆,加载起来会很慢。

这时候咱们须要将文件拆分红多个小文件,分模块打包,使用webpage的require.ensure,加上chunk名,chunk名相同的会被打包到同一个js文件里面。

const Home = resolve => {
    require.ensure(['./views/index.vue'], () => {
        resolve(require('./views/index.vue'), 'chunkname1');
    });
};

const List = resolve => {
    require.ensure(['./views/list.vue'], () => {
        resolve(require('./views/list.vue'), 'chunkname2');
    });
};

const List2 = resolve => {
    require.ensure(['./views/list2.vue'], () => {
        resolve(require('./views/list2.vue'), 'chunkname2');
    });
};

这里要注意的是使用chunk,若是你的filename是写死的,则须要配置chunkFilename,和publicPath,如:

module.exports={
    entry:'./src/js/a.js',
    output:{
        path:path.resolve(__dirname,"./dist"),
        filename:'js/output.js',
        publicPath:"./",
        chunkFilename:'js/[name].js'
    }

或者你的filename能够写成:filename:'[name].js',则可不配置chunkFilename,和publicPath

未完待续~


关注做者吧~

clipboard.png

相关文章
相关标签/搜索