zoukankan      html  css  js  c++  java
  • vue复习笔记

    1.安装vue三种方式
    cdn引入
    下载和引入
    npm安装

    2.vue属于声明式编程,操作Dom属于命令式编程

    <script src='../js/vue.js'></script>
    <script>
    const app = new Vue({
    el: "#id", //用于要挂载的元素
    data: {

    },
    methods:{
    add:function(){}
    }
    })
    </script>

    3.Vue实例中传入的options
    el: string | HTMLElement
    data: Object | Function (组件当中data必须是一个函数)
    methods:定义属于Vue的一些方法

    4.Vue的生命周期
    beforeCreate()
    created()
    mounted()

    5.vue的template
    webstrom 文件->设置->编辑器->活动模板->vue->点击+号->live tepmlate->缩写(vue)->描述()->模板文本()->Define(选择所在文件)

    6.mustache语法

    7.v-once,v-html,v-text,v-pre(原封不动的显示出来,不解析)
    v-cloak: 在vue解析之前,div中有一个属性v-cloak
    在vue解析之后,div重没有一个属性v-clock

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

    8.v-bind(:)
    v-bind动态绑定class属性(对象语法)
    <a class="" :class=''{isActive: true, } ></a>
    <a class="" :class = "getClass()"></a>
    function getClass(){return {isActive: this.isActive}}

    v-bind动态绑定class(数组语法)
    <a :class = "['title','isActive']"></a> title 为字符串
    <a :class = "[title ,isActive]"></a> title 为变量
    <a :class = "getClass"></a> function getClass(){return [this.title, this.isActive]}

    9.动态绑定style(对象语法)
    <a :style= "{ fontSize: finalSize+'px', backgroundColor: finalColor}"></a>
    <a :style= "getStyles()"></a>

    data:{
    finalSize:200,
    finalColor: 'red'
    },
    methods:{
    function getStyle(){
    return { fontSize: this.finalSize+'px', backgroundColor: this.finalColor}
    }
    }

    动态绑定style(数组语法)
    <a :style= "[bassStyle,bassStyle1]"></a>
    data:{
    bassStyle:{
    backgroundColor: 'red'
    }
    bassStyle1:{
    fontSize: '100px'
    }
    }

    10.计算属性 计算属性可以保持在缓存中,methods不能
    计算属性一般是没有set方法,只有属性
    computed:{
    fullName:{
    set: function(newValue){
    const names = newValue.split(' ');
    this.firstName = names[0],
    this.lastName = names[1]
    },
    get: function(){
    return this.firstName +'' + this.lastName
    }


    }
    }

    11.v-on:click = "btnClick" 和v-on:click= "btnClick"
    在事件定义时,写方法时省略了小括号,但是方法本身是需要一个参数的,这个时候,Vue会默认将浏览器生产的event 事件对象作为参数传入到方法
    方法定义是,我们需要event对象,同时又需要其他参数, v-on:click= 'btnClick('ab',$event)'

    12. v-on:click.stop='' 阻止冒泡
    v-on:click.prevent='' 阻止默认行为
    v-on:keyup.enter =''
    v-on:click.once =""只执行一次

    13.v-if 中出现input输入框时,区分的时候 加入key<input key= 'abc'>

    v-if 和v-show 的却别,v-if 不存在dom中,v-show原理是display:none

    14.v-for
    v-for在遍历数组的过程中,v-for= '(value,index) in array'
    v-for 在遍历对象的过程中,如果只是获取一个值。v-for="(value,key,index in obj)"

    v-for 绑定item 提高性能,因为diff算法

    15.数组中的哪些方法是响应式
    splice,push ,pop,unshift,shift
    Vue.set(array,index,'aaa')

    16.购物车 filter,map,reduce

    17.v-model
    <input type="radio" name='sex' value="男" v-model = 'sex'>男
    <input type="radio" name='sex' value="女" v-model = 'sex'>男
    data:{
    sex: "男"
    }

    18.v-model 对应单选框时 是booblen,对应多选框是数组类型
    单选框
    <input type="checkbox" value="男" v-model = 'isAgree'>同意协议
    <button :disabled="!isArgee"></button>
    data:{
    isAgree: true
    }

    多选框
    <input type="checkbox" value="读书" v-model = 'hobbies'>读书
    <input type="checkbox" value="爬山" v-model = 'hobbies'>爬山
    <input type="checkbox" value="游泳" v-model = 'hobbies'>游泳

    data:{
    hobbies: []
    }


    19.v-select
    选择一个
    <select name ='abc' v-model="fruit">
    <option value='苹果'>苹果</option>
    <option value='香蕉'>香蕉</option>
    </select>
    data:{
    fruit: '香蕉'
    }

    选择多个
    <select name ='abc' v-model="fruits" multiple>
    <option value='苹果'>苹果</option>
    <option value='香蕉'>香蕉</option>
    </select>
    data:{
    fruits: []
    }

    20.input动态值绑定
    <label v-for= "item in originHobbies" :for="item">
    <input type='checkbox' :value="item" :id="item" v-model="hobbies">{{item}}
    </label>
    data:{
    hobbies:[],
    originHobbies: ['篮球', '足球', '乒乓球']
    }

    21.v-model修饰符
    v-model.lazy
    v-model.number
    v-model.trim

    22.注册组件的基本步骤
    1.创建组件构造器 Vue.extend()方法
    2.注册组件 Vue.component()方法
    3.使用组件 在Vue实例的作用范围内使用

    创建组件
    const cnptemp = Vue.extend({
    template:` <div> <h2></h2></div>`
    })

    注册组件
    Vue.component('my-cnptemp' , cnptemp)

    使用组件
    <my-cnptemp></my-cnptemp>

    23.全局组件和局部组件
    全局组件不用再vue实例中注册,在script中注册
    Vue.component('',)

    局部组件在vue实例中注册
    const app = new Vue({
    el:'#id',
    data:{

    },
    components:{
    cpn:cpnc,
    }
    })

    24.父组件,子组件
    <div id="app">
    <com1></com1>
    </div>

    var com1 = Vue.extend({
    template:`<div>
    父组件
    <com2></com2>
    </div>`,
    props:{}
    components:{ com2: com2}
    })

    var com2 = Vue.extend({
    template:`<div>子组件</div>`,
    })

    let app = new Vue({
    el: "#app",
    components:{com1:com1}
    })

    25.组件注册的语法糖
    注册全局组件语法糖
    Vue.component(cnp,{
    template: `<div>h1</div>`
    })

    注册局部组件语法糖
    const app = new Vue({
    el:'#id',
    data:{

    },
    components:{
    cpn:{
    template: `<div>h1</div>`,
    props:{}
    }
    }
    })

    26.组件模板抽离
    第一种
    <script type= "text/x-template" id="cpn">
    <div>template</div>
    </script>

    第二种
    <template id="cpn">
    <div></div>
    </template>

    <script >
    Vue.component('npn',{
    template: '#cpn'
    })

    const app = new Vue({
    el: 'app',
    data:{

    },
    components:{
    cpn:{
    template:"#cpn",
    props:{}
    }
    }
    })
    </script>

    27.为什么组件data必须是函数
    Vue.component('npn',{
    template: '#cpn',
    data(){
    return{
    title:'aaa'
    }
    }
    })

    因为组件是复用的,如果data数据为同一对象时,所有的组件数据会共享,使用data(){return {} } 返回一个对象时,数据不会共享

    28.父子组件通信
    父组件给子组件传递数据
    在子组件中定义props:['movies'],在父组件中引用子组件时绑定 :movies =""
    方法二:类型限制 在子组件中定义 props:{
    movies: Array
    }
    props:{
    movies:{
    type:String,
    deafult:'aaaa',
    require: true
    }

    mov:{
    type:String,
    deafult(){ //当时数组或对象时,这样写 default:[] 是错误的
    return []
    },
    require: true
    }
    }
    注意:子组件绑定props数据时,不能用驼峰命名法


    子组件给父组件传递数据
    子组件 发射自定义事件$emit this.$emit('parentEvent','参数')
    父组件监听事件v-on <childComponent @parentEvent="函数"></childComponent>

    29.v-model 绑定 props的数据时,会报警告,应该把props的数据复制一份到data中再进行处理绑定。

    30.watch 监听属性的改变
    watch:{
    movies(newValue,oldValue){

    }
    }

    31.父组件访问子组件 $children,$ref
    this.$children 返回子组件数组
    this.$ref. 返回组件

    子组件访问父组件
    this.$parent. 返回父组件

    子组件访问根组件
    this.$root. 返回根组件

    32.slot
    组件 movies
    <template id="movies">
    <div>
    <slot>默认值</slot>
    </div>
    <template>

    调用组件
    <div>
    <movies>插槽里要放的内容</movies>
    </div>
    ********************************************************************8
    具名插槽
    组件 movies
    <template id="movies">
    <div>
    <slot name="a">插槽1</slot>
    <slot name="b">插槽2</slot>
    </div>
    <template>
    调用组件movies
    <div>
    <movies>
    <span slot="a">更改插槽1</span>
    <span slot="b">更改插槽2</span>
    <movies>
    </div>

    33.作用域插槽
    父组件替换插槽的标签,但是内容由子组件来提供

    插槽组件 movies
    <template>
    <div>
    <slot :data='language'>
    <p></p>
    </slot>
    </div>
    <template/>

    调用插槽movies
    <movies>
    <template slot-scope = 'slot'>
    <span v-for= "item in slot.data">{{item}}</span>
    </template>
    <movies/>

    34.import ,export ,export default模块化 模块化使用<script></script>标签中要设定 type='module'
    <script src="info.js" type="module"></script>
    <script src="info.js" type="module"></script>

    35.webpack
    webpack 模块化打包工具
    webpack 如果要运行 必须要用node环境
    node环境为了可以正常执行很多代码,必须其中包含各种依赖的包
    npm 工具 管理包(node package manage)

    webpack.config.js webpack 配置文件
    const path = require('path')

    module.exports = {
    entry: './src/main.js' ,
    output: {
    path:path.resolve(__dirname, 'dist'),
    filename: 'bundles.js'

    },
    }

    需要用到node 包,就先npm init 初始化相关包 比如 path
    npm init 后会出现 package.json 一般依赖node 都会有package.json 文件

    npm run dev 直接在package.json 里面设置。npm 可以在里面找。 可以把webpack命令 简写到package.json中的script中

    项目中安装webpack (本地安装),防止和全局的webpack冲突

    直接webpack命令时,使用的是全局的webpack打包
    若果 用命令npm ,package.json 中的script中的 webpack命令使用的是优先本地webpack

    webpack在开发阶段使用,一般运行阶段不需要,安装时,需要--save-dev

    36.loader
    加载css文件
    在js文件中引入css require('../../style.css')
    css-loader只负责将css文件进行加载
    style-loader负责将样式添加到DOM中

    module:{
    rules:[
    {
    test:'/.css$/',
    use:['style-loader','css-loader']
    }
    ]
    }

    加载less文件
    在js文件中引入less文件 require('../../style.less')
    less-loader只负责将css文件进行加载
    less负责将less文件转换为css文件
    module:{
    rules:[
    {
    test:'/.less$/',
    use:[
    {loader:'style-loader'},
    {loader:'css-loader'},
    {loader:'less-loader'},
    ]
    }
    ]
    }

    加载图片文件
    在css中引入图片时需要 url-loader
    当图片小于limit时,图片自动转换为base64字符
    图片大于limit时,需要安装file-loader。图片打包的时候会打包到dist文件夹 所以要在 webpack.config.js中配置url路径 在output 中加入 publicPath:'dist/'
    module.exports = {
    entry: './src/main.js' ,
    output: {
    path:path.resolve(__dirname, 'dist'),
    filename: 'bundles.js',
    publicPath:'dist/'
    },
    }


    module:{
    rules:[
    {
    test:'/.(png|jpg|gif|jpeg)$/',
    use:[
    {
    loader:'url-loader'
    options:{
    limit: 1200,
    name:'img/[name].[hash:8].[ext]'
    }
    },

    ]
    }
    ]
    }


    37.webpack es6 转es5的babel
    npm install babel-loader babel-core babel-preset-env或者babel-preset-es2015
    安装babel-preset-env时,需要配置.babelrc文件

    module:{
    rules:[
    {
    test:'/.js$/',
    //include:包含
    //exclude:排除
    exclude:/(node_modules|bower_components)/,
    use:{
    loader:'babel-loader'
    options:{
    presets:[es2015]
    }
    },
    }
    ]
    }

    38.webpack 中Vue的配置
    使用vue的runtime-only运行时版本,不可有任何的template,不能编译template
    runtime-compiler版本时,可有template,因为有compiler用于编译template
    需要在webpack.config.js中配置 alias:{ "vue$": 'vue/dist/vue.esm.js'}
    module.exports ={
    'vue$':'vue/dist/vue.ems.js'
    }

    在js中 引入vue
    npm install vue --save
    import Vue from 'vue'
    const app = new Vue({
    el:"#app",
    data:{

    }
    })

    39.el和template之间的关系
    template的内容会覆盖el中的内容
    var app =new Vue({
    el:'#app',
    template:`<div>替换掉app的模板</div>`
    })

    40 .js文件抽离为.vue文件
    vue-loader 加载vue
    vue-template-compiler编译vue
    npm install vue-loader vue-template-compiler --save-dev
    module:{
    rules:[
    {
    test:'/.vue$/',
    use:['vue-loader']
    }
    ]
    }

    45.配置省略扩展名
    module.exports ={
    resolve:{
    extensions:['.js','.css','.vue']
    }
    }

    46.添加版权的plugin
    const webpack = require('webpack')
    module.exports ={
    plugins:[
    new webpack.BannerPlugin('最终版权归code所有')
    ]
    }

    47.html-webpack-plugin
    npm install html-webpack-plugin --save-dev
    修改webpack.config.js文件中plugins部分内容

    const HtmlWebpackPlugin = require('html-webpack-plugin')
    module.exports ={
    plugins:[
    new webpack.BannerPlugin('最终版权归code所有')
    new HtmlWebpackPlugin({
    template:'index.html'
    })
    ]
    }

    49.js压缩插件 uglifyjs-webpack-plugin
    npm install uglifyjs-webpack-plugin

    const UglifyJsWebapckPlugin = require(uglifyjs-webpack-plugin)
    module.exports ={
    plugins:[
    new webpack.BannerPlugin('最终版权归code所有')
    new HtmlWebpackPlugin({
    template:'index.html'
    }),
    new UglifyJsWebapckPlugin()
    ]
    }

    50.webpack-dev-server
    devserver也是作为webpack 中的一个选项,选项本身可以设置如下属性
    contentBase:为哪一个文件夹提供本地服务,默认是根目录,这里我们填写.dist
    port:端口号
    inline:页面实时刷新
    historyApiFallback:在SPA页面中,依赖HTML5的history模式

    npm isntall webpack-dev-server
    module.exports ={
    plugins:[
    new webpack.BannerPlugin('最终版权归code所有')
    new HtmlWebpackPlugin({
    template:'index.html'
    }),
    new UglifyJsWebapckPlugin()
    ],
    devServer:{
    contentBase:'/dist', //为哪一个文件夹提供本地服务,默认是根目录
    inline: true //实时监听
    }
    }

    启动webpack-dev-server二种方法
    在绝对路径中 运行webpack-dev-server
    执行命令:./modules/bin/webpack-dev-server --open 自动打开浏览器
    在全局安装webpack-dev-server
    执行命令:webpack-dev-server --open 自动打开浏览器

    51.webpack 配置文件的分离
    base.config.js 公共代码
    dev.config.js 开发所需代码
    pro.config.js 生产所需代码

    把代码其中两个文件代码合并,先安装webpack-merge
    npm isntall webpack-merge --save-dev

    在pro.config.js中 合并base.config.js文件
    const uglifyjsWebpackPlugin = require('uglifyjs-webpack-plugin')
    const webpackMerge = require('webpack-merge')
    const baseConfig = require('./base.config')

    module.exports = webpackMerge(baseConfig,{
    plugins:[
    new uglifyjsWebpackPlugin()
    ]
    })

    webpack.config.js被修改路径后
    npm run build 后 webpack 命令找不到webpack,config.js后
    要修改命令为 webpack --config ./build/pro.config.js(webpack的配置文件路径)

    配置文件改变后,base.config.js中的output路径也改变了,需要重新修改路径地址

    52.vue-cli脚手架安装
    vue-cli3
    安装:npm isntall @vue/cli -g
    初始化项目:vue create 项目名称

    当vue-cli3安装后,如果要使用vue-cli2模板,还需要安装@vue/cli-init
    安装:npm install @vue/cli-init -g
    初始化项目:vue init webpack 项目名称

    53.清除缓存。
    npm clean cache -force
    c:UserAdminstratorAppDataRoaming pm-cache删除

    54.vue runtimecompiler和runtimeOnly的区别
    runtimecomplier:template->编译成ast->render->vdom->真实dom(UI)
    import App from './App'
    new Vue({
    el: "#app",
    template:'App',
    components:{App}
    })

    runtimeonly: render->vdom->真实dom(UI)(性能更高,代码更少)
    import App from './App'
    new Vue({
    el: "#app",
    render:(h)=>h(App)
    })
    *****************************************************
    虚拟dom
    new Vue({
    el: "#app",
    render:function(createElement){
    return createElement('h2' ,
    {class: "box"}, //添加属性
    ["hello world", createElement('button',["按钮"])] //添加内容
    )
    }
    })

    55.vue-cli3
    启动配置服务 vue ui

    修改配置文件 需要建一个vue.config.js文件 会和node_modules中的vue的配置文件合并

    56.vue-router
    前端路由的核心是:改变url,但是页面不进行整体的刷新
    方法两种:
    url的hash和HTML5的history

    url的hash 也就是锚点(#),本质上是改变window.location的href属性
    我们可以通过直接赋值location.hash来改变href,但是页面不发生刷新

    history.pushState({},' ','home') history.back()
    history.replaceState({},' ','home')不能使用 hitsory.back()

    history.go(-1)
    history.forward()
    history.back()

    配置路由
    import Vue from 'vue'
    import VueRouter from 'vue-router'

    import Home from '../components/home'

    1. 通过Vue.use(插件),安装插件
    Vue.use(VueRouter)
    2. 创建VueRouter对象
    const routers = [
    {
    path:'',
    redirect:'Home'
    },
    {
    path:'/home',
    component:'Home'
    },
    {
    path:'/home',
    component:'About'
    }

    ]

    const router = new VueRouter({
    routers:routers
    mode:'history' history模式

    //linkActiveClass把<router-link>中属性active-class的值router-link-active改为active
    linkActiveClass: 'active'
    })
    3.将router对象导入到Vue实例
    export default router

    <router-link to ="/home" tag='button' replace active-class="router-link-class"></router-link>
    <router-view></router-view>

    <router-link>属性
    tag="button" router-link改变成button标签
    replace 不能返回和后退
    router-link-active 活跃的标签自动带有的属性 active-class="router-link-active"

    this.$router.push('/home')
    this.$router.replace('/home')

    57.动态路由
    const routers = [
    {
    path:'/home/:id',
    component:'Home'
    },
    ]

    <router-link to="/home/12"></router-link>
    获取参数 this.$route.params.id

    58.路由的懒加载
    const routers = [
    {
    path:'/home/:id',
    component:()=>import('../component/Home')
    },
    ]

    59.路由的嵌套
    const News = ()=>import('../component/news')
    const routers = [
    {
    path:'/home',
    component:()=>import('../component/Home')
    children:[
    {
    path:'',
    redirect:'news'
    },
    {
    path:'news',
    component: News
    }

    ]
    },
    ]

    60.vue-router参数传递
    params类型 是push的对象路径只能用name
    this.$router.push({
    name:'/home',
    query:{
    id:'',
    }
    })

    /router/:id
    <router-link to="/home/12"></router-link>
    <router-link :to="'/home/'+id"></router-link>
    获取参数 this.$route.params.id

    query类型
    this.$router.push({
    path:'/home',
    query:{
    id:'',
    }
    })

    /router?id=123
    <router-link :to={path:'/home',query: {id: '123', value: 'heihei'} }></router-link>
    取参数
    this.$route.query.id

    61.全局导航守卫
    const router = new VueRouter({
    routers:[
    {
    path:'/home',
    meta:{ //元数据(描述数据的数据)
    title:'首页'
    },
    component: ()=>import('../component/Home')
    }
    ]

    })

    前置守卫
    router.beforeEach((to, from ,next)=>{
    document.titile= to.matched[0].meta.title

    })

    后置钩子
    router.afterEach((to, from )=> {


    })

    62.路由独享守卫

    const router = new VueRouter({
    routers:[
    {
    path:'/home',
    component: ()=>import('../component/Home'),
    router.beforeEach((to, from, after)=>{

    })
    }
    ]

    })
    63.组件内的守卫
    beforeRouterEnter(){}
    beforeRouterUpate(){}
    beforeRouterLeave(){}

    64.vue-router-keep-alive
    keep-alive是Vue内置的一个组件,可以使被包含的组件保留状态,或避免重新渲染

    keep-alive中有两个非常重要的属性
    include: 字符串或正则表达式,只有去陪的组件会被缓存
    exclude: 字符串或正则表达式,任何区配的组件都不会被缓存
    <keep-alive eclude ='home,profile'>
    <outer-view><router-view/>
    </keep-alive>
    export default{
    name: 'home',
    data(){},
    created(){}
    }


    这两个函数,只有该组件被保持了状态使用了keep-alive时,才是有效的
    activated(){}
    deactivated(){}

    router-view也是一个组件,如果直接被包含在keep-alive里面,所有路径区配到的视图组件都会被缓存

    65.底部tabbar 组件封装
    TabBar实现思路
    1.如果在下方有一个单独的TabBar组件,你如何封装
    自定义TabBar组件,在App中使用
    让TabBar处于底部,并且设置相关的样式
    2.TabBar中显示的内容由外界决定
    定义插槽
    flex布局评分TabBar
    3.自定义TabBarItem,可以传入图片和文字
    定义TabBarItem,并且定义两个插槽:图片、文字。
    给两个插槽外层包装div,用于设置样式
    填充插槽,实现底部TabBar的效果

    vue init webpack tabbar
    1.新建TabBar.vue 组件文件
    <template>
    <div id= 'tab-bar'>
    <slot></slot>
    </div>
    </template>
    <script>
    export default {
    name: 'TabBar'
    }
    </script>

    2.新建TabBarItem组件
    <template>
    <div id= 'tab-bar-item' @click="itemClick">
    //<img src="../../assets" alt="">
    //<div></div>
    <div v-if="!isActive">
    <slot name ='item-icon'></slot>
    </div>

    <div v-else>
    <slot name ='item-icon-active'></slot>
    </div>
    <div :class="activeStyle">
    <slot name = 'item-text'></slot>
    </div>

    </div>
    </template>
    <script>
    export default {
    name: 'TabBarItem',
    props:{
    path: String,
    activeColor:{
    type:String,
    default:'red'
    }
    }
    data(){
    return{
    isActive:false
    }
    },
    computed:{
    isActive(){
    return this.$route.path.indexOf(this.path)!==-1
    },
    activeStyle(){
    return this.isActive?{color:this.activeColor}:{}
    }

    },
    methods:{
    itemClick(){
    this.$router.replace(this.path)
    }
    }
    }
    </script>
    <style>
    .active{
    color:red;
    }
    </style>

    3.封装MainTabBar
    <template>
    <tab-bar>
    <tab-bar-item path="/home" activColor="blue">
    <img slot="item-icon" src="./assets/img/">
    <img slot="item-icon-active" src="./assets/img/">
    <div slot="item-text">首页</div>
    <tab-bar-item>
    <tab-bar-item path="/my" activColor="blue">
    <img slot="item-icon" src="./assets/img/">
    <img slot="item-icon-active" src="./assets/img/">
    <div slot="item-text">我的</div>
    <tab-bar-item>
    </tab-bar>
    </template>
    <script>
    import TabBar from '../components/tabbar/TabBar'
    import TabBarItem from '../components/tabbar/TabBarItem'
    export default{
    name: 'MainTabBar',
    components:{
    TabBar,
    TabBarItem
    }
    }
    </script>

    4.调用MainTabBar组件

    66.promise
    方法一:
    new Promise(function(resolve,reject){
    retrun new Pormise(reslove,reject){
    resolve(data)
    }
    }).then(function(data){
    console.log(data)
    })

    简写成
    new Promise(function(resolve,reject){
    retrun Promise.resolve(data)
    }
    }).then(function(data){
    console.log(data)
    })

    还可以简写为
    new Promise(function(resolve,reject){
    retrun data
    }
    }).then(function(data){
    console.log(data)
    })

    处理错误reject
    new Promise(function(resolve,reject){
    retrun new Pormise(reslove,reject){
    resolve(data)
    }
    }).then(function(data){
    console.log(data)
    }).catch( err =>{
    console.log(err)
    })

    new Promise(function(resolve,reject){
    retrun new Pormise(reslove,reject){
    resolve(data)
    }
    }).then( res=>{
    throw 'error message'
    }).catch( err =>{
    console.log(err)
    })

    new Promise(function(resolve,reject){
    retrun new Pormise(reslove,reject){
    resolve(data)
    }
    }).then( res=>{
    return Pormise.reject('error message')
    }).catch( err =>{
    console.log(err)
    })

    67.promise.all
    Promise.all([
    new Promise((resolve,reject) =>{
    resolve('result')
    }),
    new Promise((resovle,reject)=>{
    resolve('result')
    })
    ]).then(results=>{
    console.log(results)
    })

    68.Vuex 是一个专为vue.js应用程序开发的状态管理模式
    state 单一状态树

    npm install vuex
    新建一个store文件夹,创建index.js
    import Vue from 'vue'
    import Vuex from 'vuex'

    1.安装插件
    Vue.use(vuex)
    2.创建对象
    const store = new Vuex.Store({
    state :{
    counter:1000
    },
    mutations:{ //修改状态,通过commit('')修改提交
    modifyState(state){
    state.counter++
    },
    incrementCount(state,count){ //带参数 payload:负载
    state.counter += count
    }

    },
    actions :{ //异步修改状态,再进行mutations的修改。dispatch

    },
    getters :{ //类似计算属性
    powerCounter(state){
    return state.counter*statecounter
    },
    more20Stu(state){
    return state.students.filter(s=>s.age>20)
    },
    more20StuLength(state,getters){
    return getters.more20Stu.length
    },
    moreAgeStu(state){ //带参数
    return function(age){
    return state.students.filter(s => s.age > age)
    }

    // return age => { return state.students.filter(s => s.age > age)}
    }

    },
    modules:{ //划分模块,针对不同模块进行相关数据保存

    }
    })


    3.导出
    export dafault store

    4.在main.js中 注册vuex
    import stroe form './store'
    Vue.prototype.$store = store
    new Vue({
    el: '#app',
    store, // Vue.prototype.$store = store
    render: h=>h(App)
    methods:{
    increment:function(){
    this.$store.commit('modifyState')
    }
    }
    })

    69.vuex.....
    mutation提交方式
    1.普通提交
    this.$store.commit('modifyState',counter)

    vuex对象的mutations
    mutations:{
    modifyState(state,counter){ //counter参数为commit中的counter
    state.conter += counter
    }
    }

    2.特殊提交
    this.$store.commit({
    type:'modifyState',
    counter
    })

    vuex对象的mutations的
    mutations:{
    modifyState(state,payload){ //payload参数为commit提交的{ type:'modifyState',counter}
    state.conter += payload.counter
    }
    }

    Mutation响应规则
    vuex的store中的state是响应式的,当state中的数据发生改变时,Vue组件会自动更新
    这就要求我们必须遵守一些Vuex对应的规则

    响应式的方法有splice,push ,pop,unshift,shift 同15条方法相同

    1.提前在store中初始化好所需的属性

    2.方式一: 使用Vue.set(obj,'newProp',123)

    Vue.set(state.info,'age','13')

    方式二: 用新对象给旧对象重新赋值

    state.info={...state.info,'age':payload.height}

    删除state数据中对象的属性
    Vue.delete(obj,'pro') //Vue.delete(state.info,'age')

    Mutations的类型常量

    新建mutations-types.js
    export const METHODSNAME = 'methodsName'

    在store的mutations中引入常量
    import {METHODSNAME,} from 'mutations-types.js'
    mutations:{
    [METHODSNAME](state){
    state.counter++
    }

    }

    组件中使用mutations
    引入
    import {METHODSNAME,} from 'mutations-types.js'
    调用
    this.$store.commit(METHODSNAME)



    Actions 异步修改state时用 action,在action中调用mutations,不能直接在action中修改state
    mutations:{
    modifyState(state){
    state.age = '12'
    } ,
    Action(context,payload){
    return new Promise((resolve,reject)=>{
    setTimeout(()=>{
    context.commit('modifyState')
    console.log(payload)

    resolve('11')
    },1000)
    })
    }
    }

    调用
    this.$store
    .dispatch('modifyState','参数')
    .then(res => {
    console.log(res)
    })


    modules:
    modules:{
    a:{
    state:{},
    getters:{},
    mutations:{},
    actios:{},
    }
    }

    const moduleA ={
    state:{},
    getters:{
    fullname(state){
    return state.name
    },
    fullname(state,getters){
    return getters.name
    },
    fullname(state,getters,rootState){ //rootState的是根部的state
    return getters.name +rootState.name
    },

    },
    mutations:{},
    actions:{
    updateName(context){
    setTimeout(()=>{
    context.commit('updateName','')
    })
    }
    },
    }

    const store =new Vuex.store({
    state:{},
    getters:{},
    mutations:{},
    actios:{},
    modules:{
    a:moduleA
    }
    })


    调用: modules中的a的state被放入 store中的state里面
    this.$store.state.a.name

    this.$store.commit()

    vuex的文件夹的目录组织...

    70.axios
    https://httpbin.org 网路服务器
    axios请求方式
    axios(config)
    axios.quest(config)
    axios.get(url[,config])
    axios.delete(url[,config])
    axios.head(url[,config])
    axios.post(url[,data[,config]])
    axios.put(url[,data[,config]])
    axios.patch(url[,data[,config]])

    npm install axios --save
    import axios from 'axios '

    axios({
    methods:get //默认为get
    url:'http://',
    params:{
    type:
    }

    }).then(()=>{

    })

    axios.get('http://',{params:{type:}})


    发送多个请求
    axios.all([axios(),axios()])
    .then(results=>{
    console.log(results[0])


    })

    axios.spread(()=>{}) 可以结构多个并发请求的结果
    或者
    axios.all([axios(),axios()])
    .then(axios.spread((res1,res2)=>{

    }))


    71.全局配置
    在开发中可能很多参数都是固定的,这个时候我们可以进行一些抽取,可以利用axios的全局

    axios.defaults.baseURL = 'http://100.1.1.1'
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencode'
    axios.defaults.timeout= 5000

    常见的配置选项:

    请求地址:url:'/user'
    请求类型:method:'get'
    请求路径:baseURL:'http://www.'
    请求前的数据处理:transformRequest:[function(data){}]
    请求后的数据处理:transformRequest:[function(data){}]
    自定义的请求头:header:{'x-Requested-With':‘XMLHttpRequest’}
    URL查询对象:params:{id:12}
    查询对象函数:paramsSerializer:function(params){}
    设置超时s:timeout:1000,
    跨域是否携带token:withCredentials:false
    request body :data:{key:'aa'},
    自定义请求处理:adapter:function(resolve,reject,config){}
    身份验证信息:auth:{uname:'',pwd:'12'}
    响应的数据格式json/blob/text/stream../:responseType:'json'

    72.axios的实例和模块封装
    创建对应的axios的实例
    const instance1 =axios.create({
    baseURL : 'http://www.baidu.com'
    timeout:3000
    })
    instancel({
    url:'pop',
    page:1
    }).then(res=>console.log(res))

    创建第二个实例
    创建对应的axios的实例
    const instance2 =axios.create({
    baseURL : 'http://www.wangyi.com'
    timeout:3000
    })
    instance2({
    url:'pop',
    page:1
    }).then(res=>console.log(res))

    封装在request.js中
    import axios from axios
    export function request(config){
    return new Promise((resolve,reject)=>{
    const instance = axios.create({
    baseURL:'http://www.baidu.com',
    timeout:1000,
    })

    instance.axios(config)
    .then(res=>{
    resolve(res)
    })
    .catch(err=>{
    reject(err)
    })

    })
    }

    export function request(config){
    const instance = axios.create({
    baseURL:'http://www.baidu.com',
    timeout:1000,
    })
    retrun instance.axios(config)

    }

    73.axios请求方式
    支持多种请求方式
    axios(config)
    axios.request(config)
    axios.get(url[,config])
    axios.delete(url[,config])
    axios.head(url[,config])
    axios.post(url[,data[,config]])
    axios.put(url[,data,[,config]])
    axios.put(url[,data,[,config]])

    网络请求地址:httpbin.org/


    1.axios的基本使用

    axios({
    url:'http:/www/8080/interface',请求
    methods: 'get', //默认为get
    baseURL:'' //单独配置
    })
    .then( res =>{
    console.log(res)
    })


    axios({
    url: 'http://interface',
    //params专门针对get请求参数的拼接
    params:{

    }
    })


    2.axios发送并发请求
    axios.all([axios({
    url : 'http://inferface'
    }),axios({
    url : 'http://inferface',
    params:{
    type: 'cell',
    page: 5
    }
    })])
    .then(result = >{
    console.log(result[0]) //result 是一个数组结果是两个axios的结果
    })

    axios.all([axios({

    url : 'http://inferface'
    }),axios({
    url : 'http://inferface',
    params:{
    type: 'cell',
    page: 5
    }
    })])
    .then(axios.spread((res1,res2)=>{ //spread 把两个axios的结果展开
    console.log(res1)
    }))


    3.axios的配置信息
    全局配置
    axios.defaults.baseURL = '123.222.111.11:8080'
    axios.dafaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
    axios.defaults.timeout = 5000

    axios({
    url:'http:/www/8080/interface',请求
    methods: 'get', //默认为get
    baseURL:'' //单独配置
    })
    .then(res=>{

    })

    常见的配置选项
    //请求地址
    url:'/user'

    //请求类型
    method: 'get'

    //请求路径
    baseURL:'http://www.baidu.com'

    //请求前的数据处理
    transformRequest:[function(){}]

    //请求后的数据处理
    transformResponse:[function(){}]

    //自定义的请求头
    headers:{'x-Requested-With':'XMLRequest'}

    //URL查询对象
    params:{id:12} 针对get请求

    //查询对象序列化函数
    paramsSerializer:function(params){}

    //request body
    data:{key : 'a'} 针对post请求

    //超时设置
    timeout : 1000

    //跨域是否带Token
    withCredentials : false

    //自定义请求处理
    adpater: fucntion(resolve,reject,config){}

    //身份验证信息
    auth : {uname : '', pwd : '123'}

    //响应的数据格式json/blob/document/arraybuffer/text/stream
    responseType : 'json'

    4.axios实例
    创建对应的axios的实例
    const instance = axios.create({
    baseURL: 'http://122.111',
    timeout: 5000
    })

    instance({
    url: '/home/multidata'
    })
    .then(res=>{
    console.log(res)
    })

    const instance2 = axios.create({
    baseURL: 'http://122.111',
    timeout: 5000
    })

    instance2({
    url: '/home/multidata'
    })
    .then(res=>{
    console.log(res)
    })

    5.封装axios
    import axios from 'axios'
    //config = {baseURL: 'http://',timeout:5000}
    封装一
    export function request(config,success,failtrue){
    //1.创建axios实例ss,failtrue
    const instance = axios.create({
    baseURL:'http://',
    timeout: 5000
    })
    instance(config)
    .then(res =>{
    success(res)
    })
    .catch(err=>{
    failtrue(err)
    })
    }
    调用一:
    request({
    url:'',
    timeout:''
    },
    res=>{},
    error =>{})

    封装二
    export function request(config){
    //1.创建axios实例ss,failtrue
    const instance = axios.create({
    baseURL:'http://',
    timeout: 5000
    })
    instance(config.baseConfig)
    .then(res =>{
    config.success(res)
    })
    .catch(err=>{
    config.failtrue(err)
    })
    }
    调用二:
    request({
    baseConfig: {
    url:'',
    timeout:5000,
    },
    success:function(){},
    failtrue:function(){}
    })

    封装三
    export function request(config){
    return new Promise((reslove,reject)=>{
    const instance = axios.create({
    baseURL:'http://',
    timeout: 5000
    })
    //发送网络请求
    instance(config)
    .then(res=>{
    resolve(res)
    })
    .catch(err=>{
    reject(err)
    })
    })
    }
    调用三
    request({
    url:'http://'
    })
    .then(res=>{

    })

    封装四
    export function request(config){
    const instance = axios.create({
    baseURL:'http://',
    timeout: 5000
    })
    //发送网络请求
    return instance(config)
    }
    调用三
    request({
    url:'http://'
    })
    .then(res=>{

    })


    拦截器
    配置请求和响应拦截

    请求拦截
    instance.interceptors.request.use(config=>{
    console.log(config)
    //比如config中的一些信息不符合服务器的要求

    //比如在每发送网络的时候,都希望界面显示一个请求的图片

    //某些网络请求比如登录(token),比如携带一些特殊的信息

    return config

    },err=>{
    console.log(err)
    })

    响应拦截
    instance.interceptors.response.use(res=>{
    console.log(res)

    return res.data
    },err=>{
    console.log(err)
    })

    74.项目 用vue-cli3

    github 中搜索 Normalize.css 初始化css

    一.
    npm create mall

    github 托管
    将已有代码托管到 github中
    git remote add origin https://github....
    git push -u origin master

    二.npm install

    三.划分目录结构
    src目录中
    main.js
    App.vue
    views->home/category
    components->common/content
    assets->css/img->css(->normalize.css/base.css)/
    router->
    store->
    network->request.js/home.js/user.js/cart.js
    common->untils.js(工具)/const.js(常量)/mixin.js

    四.vue-cli3中的webpack配置项隐藏在node_modules中的vue/cli-service下

    vue.config和editorconfig

    在根目录创建vue.config.js修改配置文件 会和隐藏的配置合并
    module.exports = {
    configureWebpack:{
    resolve:{
    alias:{ 配置别名
    'common': '@/common'
    'assets': '@/assets'
    'components': '@/components'
    'network': '@/network'
    'views': '@/views'

    }

    }
    }

    }

    在url或DOM中是用别名的时候前缀加~
    src="~common/css/base.css"

    创建editorconfig,用来同意代码风格


    创建项目
    1.封装navBar
    新建NavBar.vue
    <template>
    <div class="nav-bar">
    <div class="left">
    <solt name="left"></solt>
    </div>
    <div class="center">
    <solt name="center"></solt>
    </div>
    <div class="right">
    <solt name="right"></solt>
    </div>
    </div>
    </template>
    <script></script>
    <style scoped>
    .nav-bar{
    display: flex;
    height:44px;
    line-height:44px;
    text-align:center;
    box-shadow:0 1px 1px rgba(100,100,100,1)
    }
    .left,.right{
    60px;
    }
    .center{
    flex:1;
    }
    </style>

    2.封装网络请求,先封装一个axios请求,每个文件模块封装一个网络请求
    一:
    封装一个axios实例请求 request.js
    export function request(config){
    const instance = axios.create({
    baseURL:'http://',
    timeout: 5000
    })
    //发送网络请求
    return instance(config)
    }
    二:封装home,多个home的网络请求,方便管理
    封装home.js请求
    import {request} from './request'
    export function getHomeMultidata(){
    return request({
    url: '/home/multidata'
    })
    }
    export function getHomeMultidata(){
    return request({
    url: '/home/multidata'
    })
    }

    75.Better-scroll的基本用法
    默认情况下BScroll是不可以实时监听滚动位置
    probe侦测
    0,1都是不侦测实时的位置
    2:在手指滚动的过程中侦测,手指离开后的惯性滚动过程中不侦测
    3:值要是滚动,都侦测

    const bscroll = new BScroll(document.querySelect('.content'),{
    probeType: 3,
    click: true, //div元素是否可点击
    pullUpload:true

    })

    bscroll.on('srcoll',(position)=>{
    console.log(position)
    })

    bscroll.on('pullingUp',()=>{
    console.log('上拉加载更多')
    //发送网络请求,请求更多页的数据

    //等待数据请求完成,并且将新的数据展示出来后
    setTimeout(()=>{
    bscroll.finishPullUp()
    },2000)

    })

    76.事件总线
    Vue.prototype.$bus = new Vue()
    Vue.$bus.$emit('event',参数)
    Vue.$bus.$on('event')

    77.防抖函数
    防抖debounce/节流throttle

    debounce(func,delay){
    let timer = null

    return function(...args){
    if(timer) clearTimeout(timer)

    timer = setTimeout(()=>{
    func.apply(this, args)
    },delay)
    }
    }

    const refresh = this.debounce(this.$refs.scroll.refresh)

    this.$bus.$on('itemImageLoad',()=>{ refrsh()})
    ...............................................................................................

  • 相关阅读:
    [转]利用docker进行java开发小demo
    markdown简介及语法
    Thinking in Java 之classpath理解
    docker官方windows安装
    Thinking in Java笔记之类及对象的初始化
    开发工具之play framework
    图解phpstorm常用快捷键
    Git相关
    Yii 1.1 cookie删不掉
    ajax跨域,这应该是最全的解决方案了
  • 原文地址:https://www.cnblogs.com/bydzhangxiaowei/p/12249104.html
Copyright © 2011-2022 走看看