vue学习笔记

vue

介绍 — Vue.js (vuejs.org)

特点

渐进式

vue 安裝

​ 1.在线地址引入

<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

<!-- 生产环境版本,优化了尺寸和速度 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>

​ 2.下载 vuejs.org/js/vue.js

​ 3.npm安装 webpack cli

## let 和const 区别

let 变量 const 常量

mvvm的理解

MVVM是什么: mvvm是 Model-View-ViewModel 的缩写,即 模型-视图-视图模型。

Model:数据模型,后端传递的数据。
View:代表 UI 组件,它负责将数据模型转化成 UI 展现出来
ViewModel:是一个同步View 和 Model的对象。MVVM模式的核心,它是连接Model和View的桥梁。

前端开发中暴露出了三个痛点问题:

开发者在代码中大量调用相同的 DOM API,处理繁琐 ,操作冗余,使得代码难以维护。
大量的 DOM 操作使页面渲染性能降低,加载速度变慢,影响用户体验。
当 Model 频繁发生变化,开发者需要主动更新到 View ;当用户的操作导致 Model 发生变化,开发者同样需要将变化的数据同步到 Model 中,这样的工作不仅繁琐,而且很难维护复杂多变的数据状态。

早期 jquery 的出现就是为了前端能更简洁的操作 DOM 而设计的,但它只解决了第一个问题,另外两个问题始终伴随着前端一直存在。
MVVM优点:

在MVVM架构下,View 和 Model 之间并没有直接的联系,而是通过 ViewModel 进行交互,Model 和 ViewModel 之间的交互是双向的, 因此 View 数据的变化会同步到 Model 中,而 Model 数据的变化也会立即反应到View 上。
ViewModel 通过双向数据绑定把 View 和 Model 连接了起来,而 View 和 Model 之间的同步工作完全是自动的,无需人为干涉,因此开发者只需关注业务逻辑,不需要手动操作DOM, 不需要关注数据状态的同步问题,复杂的数据状态维护完全由 MVVM 来统一管理。

总结:在MVVM的框架下视图和模型是不能直接通信的,它们通过ViewModel来通信。
ViewModel通常要实现一个Observer观察者,当数据发生变化,ViewModel能够监听到数据的这种变化,然后通知到对应的视图做自动更新,而当用户操作视图,ViewModel 也能监听到视图的变化,然后通知数据做改动,这实际上就实现了数据的双向绑定。并且MVVM中的View 和 ViewModel可以互相通信。

基础语法

{{}} for循环

​ let i in/of this.books

​ for增强版

<div id="app"></div>
const app = new Vue({
	el:"#app",
	data:{
		messgae:"",
		movies:[]
	}
})
{{}}
v-for=“ movie in movies”
  • 数据展示
  • 列表数据
  • @click点击事件 点击函数
  • {{ + * + ” “+}} 支持一些运算符

methods 方法

  • methods this
methods:{
	add:function(){
		this.number--
	},
	down:function(){
		this.number++
	}
}

v-bind 动态绑定属性

  • html标签的属性是不能通过{{}}赋值的 :src=""
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <style>
        .active {
            color: aqua;
        }
    </style>
</head>
<body>
    <div id="app">
        <ul>
            <li v-for="(m,index) in movies"
             @click="btnClick(index)"
             :class="{active:currentIndex==index}">
                {{index}}-{{m}}
            </li>
        </ul>
    </div>
    <script>
        const app = new Vue({
            el: '#app',
            data: {
                currentIndex: 0,
                movies: ['hello', 'zcc', 'world']
            },
            methods: {
                btnClick: function (index) {
                    this.currentIndex = index;
                }
                ,btnClick2(){
                    console.log(1111)
                }
            }
        })
    </script>
</body>
</html>

computed 计算

  • get set 方法
  • 计算属性缓存

v-on 修饰符

  • @cilck

  • @click.stop 阻止冒泡

  • @click.prevent 阻止默认的提交

  • @click.once

  • @keyup.enter

  • $event

  • v-once

  • v-html

  • v-pre

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <!-- 开发环境版本,包含了有帮助的命令行警告 -->
        <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
        <title>Document</title>
    </head>
    <body>
        <div id="app">
            <h1 :style=[style1,style2]>这是一个大标题</h1>
            <button @click="btnClick">按钮1</button>  
            <div style="width: 300px;height: 200px;" @click="btnClick2">
                <button @click.stop="btnClick21">按钮2</button>
            </div>
            <form action="" method="GET">
                <input type="submit" value="提交" @click.prevent="btnClick21">
            </form>
            <button @click.once="btnClick21">按钮4</button>  
            <button >按钮5</button>
            <input  @keyup="btnClick21" type="text">
            <input  @keydown="btnClick21" type="text">
            <input  @keyup.enter="btnClick21" type="text">
            <input  @keyup.k="btnClick21" type="text">
        </div>
        <script>
            const app = new Vue({
                el: "#app",
                data: {
                    number: 1
                    ,movies:["哆啦A梦","消息队列","大笨蛋"]
                    ,style1:{ color:"red"}
                    ,style2:{ 'font-size':"22px"}
                }
                ,methods:{
                    btnClick(name){
                        console.log(1111)
                        console.log(name)
                    }
                    ,btnClick2(){
                        console.log("div2点击")
                    }
                    ,btnClick21(){
                        console.log(1111)
                    }        
                }
            })
        </script>
    </body>
    </html>
    

if else -if else

  • if else 复用的问题 key

Arr 常用数组

  • unshit 前面添加
  • shift 删除
  • pop 删除
  • push 添加
  • splice 删除并且替换
  • sort
  • reverse
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <title>Document</title>
</head>

<body>
    <div id="app">
        <ul>
            <li v-for="movie in movies">
                {{movie}}
            </li>
        </ul>
        <button @click="splice">点击</button>
    </div>

    <script>
        const app = new Vue({
            el: "#app",
            methods:{
                unshift(){
                    this.movies.unshift("aaa")
                }
                ,push(){
                    this.movies.push("zzz")
                }
                ,shift(){
                    this.movies.shift()
                }
                ,pop(){
                    this.movies.pop()
                }
                ,splice(){
                    this.movies.splice(1,0,"z","s","a","c")
                }
            },
            data: {
                number: 1,
                movies:["哆啦A梦","消息队列","大笨蛋","1111","222"]
            }
        })
    </script>
</body>

</html>

购物车

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <!-- 开发环境版本,包含了有帮助的命令行警告 -->    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>    <title>Document</title></head><body>    <div id="app">        <table>            <thead>                <th></th>                <th>书籍名称</th>                <th>出版日期</th>                <th>价格</th>                <th>购买数量</th>                <th>操作</th>            </thead>            <tbody>                <tr v-for="(item,index) in cart">                    <td>{{item.id}}</td>                    <td>{{item.bookName}}</td>                    <td>{{item.publishTime}}</td>                    <td>{{ item.price | showPrice}}</td>                    <td>                        <button @click="down(index)" :disabled="item.num==1">                            -                        </button>                        {{item.num}}                        <button @click="up(index)">                            +                        </button>                    </td>                    <td>                        <button @click="del(index)">移除</button>                    </td>                </tr>            </tbody>        </table>        <h1>总价为:{{getTotalPrice | showPrice}}</h1>    </div>    <script>        const app = new Vue({            el: "#app",            methods:{                up(index){                    this.cart[index].num++;                },                down(index){                    this.cart[index].num--;                },                del(index){                    this.cart.splice(index,1)                }            },            data: {                number: 1,                totalPrice:0,                movies:["哆啦A梦","消息队列","大笨蛋"],                cart:[                    {                        id:1,                        bookName:"算法导论",                        publishTime:"2006-9",                        price:22,                        num:1                    },                    {                        id:2,                        bookName:"UNIX编程艺术",                        publishTime:"2020-8",                        price:59,                        num:2                    },                    {                        id:3,                        bookName:"编程规范",                        publishTime:"2008-9",                        price:66,                        num:1                    },                    {                        id:4,                        bookName:"代码大全",                        publishTime:"2006-3",                        price:33,                        num:1                    },                ]            },            filters:{                showPrice(value){                    return "¥"+value.toFixed(2)                }            },            computed:{                getTotalPrice(){                    let total = 0;                    for(let i = 0 ;i < this.cart.length;i++){                        total+= this.cart[i].price * this.cart[i].num                                        return total;                }            }        })    </script></body></html>

v-model 双向绑定

​ 单选

​ 全选

​ 下拉列表

### v-model 修饰符

.lazy

.number

.trim

组件化

创建组件的构造器 ,注册组件

### 全局组件和局部组件

​ 全局组件

Vue.component('cp1',{            template:`                <div>                    <h2>我是标题1</h2>                    <p>我是内容,哈哈哈</p>                </div>            `        })

局部组件

   const app = new Vue({            el: "#app",            components:{                'cpn2':{                    template:`                        <div>                            <h2>我是标题2</h2>                            <p>我是内容,哈哈哈</p>                        </div>                    `                }            }        }) 

模板的分离写法

	 <template id="cp1">         <div>             <h2>我是标题</h2>             <P>我是内容</P>         </div>     </template>
VUe.component('cp1',{	template:"#cp1"})
const app = new Vue({	el:"#app",	components:{		'cpn2':'#cpn2'	}})

事例

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <!-- 开发环境版本,包含了有帮助的命令行警告 -->    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>    <title>Document</title></head><body>    <div id="app">        <count></count>        <count></count>        <count></count>        <count></count>    </div>    <template id="count">        <div>            <button @click="add">-</button>            <span>{{number}}</span>            <button @click="down">+</button>        </div>    </template>    <script>        Vue.component('count',{            template:"#count",            data(){                return {                    number:0                };            },            methods:{                add(){                    this.number--;                },                 down(){                    this.number++;                }            }        })        const app = new Vue({            el: "#app",                })    </script></body></html>

父传子-组件通信

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <!-- 开发环境版本,包含了有帮助的命令行警告 -->    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>    <title>Document</title></head><body>    <div id="app">        <count :cmovies="movies" :cmessage="message"></count>    </div>    <template id="count">        <div>            <button @click="add">-</button>            <span>{{number}}</span>            <button @click="down">+</button>            <span v-for="m in cmovies">{{m}}</span>            <span v-for="ms in cmessage">{{ms}}</span>        </div>    </template>    <script>        const a = Vue.component('count',{            template:"#count",            props:["cmovies","cmessage"],            data(){                return {                    number:0                   };            },            methods:{                add(){                    this.number--;                },                 down(){                    this.number++;                }            }        })        const app = new Vue({            el: "#app",            data:{                movies:["哆啦A梦","消息队列","大笨蛋"],                message:"这是messgae"            }                })    </script></body></html>

子传父

​ 子组件发射事件 引用标签的时候关联事件 在父组件输出事件

 //发射事件this.$emit("item-click");
 <count :cmovies="movies" :cmessage="message" @item-click="cpnclick"></count>
     const app = new Vue({            el: "#app",            data:{                movies:["哆啦A梦","消息队列","大笨蛋"],                message:"这是messgae"            },            methods:{                cpnclick(){                    console.log("父组件")                }            }                })

$children , $refs

插槽

具名插槽

 <div id="app">        <count :cmovies="movies" :cmessage="message" @item-click="cpnclick">            <button>这是插槽</button>        </count>    </div>    <template id="count">        <div>            <button @click="add">-</button>            <span>{{number}}</span>            <button @click="down">+</button>            <span v-for="m in cmovies">{{m}}</span>            <span v-for="ms in cmessage">{{ms}}</span>            <slot name="left"></slot>            <slot></slot>        </div>    </template>

vue 插槽作用域

​ 模板

    <template id="count">        <div>            <slot :data="movies"></slot>        </div>      </template>

​ 主应用

  <div id="app">        <count>            <template slot-scope="slot">                <span v-for="item in movies">{{item}} - </span>            </template>        </count>    </div>

​ 或者

   <div id="app">        <count>            <template slot-scope="slot">                <span>{{slot.data.join('-')}}</span>            </template>        </count>    </div>

模块化开发

### 导入 导出

导出

export{}

export let num = 1000;

export let height = 200;

export function total(num1,num2){}

导入

import {num1,num2} from “./js”

import * as aaa from “./js”

common.js 模块化规范

const {} = require()

webpack

安装node

node -v

安装 webpack 3.6

npm install webpack@3.6.0 -g

webpack 打包

npm init 生成路径配置 package.json

{  "name": "mett",  "version": "1.0.0",  "main": "webpack.config.js",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1"  },  "author": "",  "license": "ISC",  "description": ""}

打包配置文件 webpack.config.js

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

开发时依赖webpack

npm install webpack@3.6.0 --save-dev

package.json

{  "name": "mett",  "version": "1.0.0",  "main": "webpack.config.js",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1",    "build": "webpack"  },  "author": "",  "license": "ISC",  "description": "",  "dependencies": {    "build": "^0.1.4"  },  "devDependencies": {    "webpack": "^3.6.0"  }}

安装loader 加载 css

{  "name": "mett",  "version": "1.0.0",  "main": "webpack.config.js",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1",    "build": "webpack"  },  "author": "",  "license": "ISC",  "description": "",  "dependencies": {    "build": "^0.1.4"  },  "devDependencies": {    "css-loader": "^2.0.2",    "style-loader": "^0.23.1",    "webpack": "^3.6.0"  }}
const path = require('path')module.exports = {    entry:'./src/main.js',    output:{        path: path.resolve(__dirname,'dist'),        filename:'bundle.js'    },    module: {        rules: [            {                test: /\.css$/,                use:['style-loader','css-loader']            }        ]    }}
npm install --save-dev css-loader@2.0.2
npm install --save-dev style-loader@0.23.1

less 安装

npm install --save-dev url-loader@1.1.2
npm install --save-dev file-loader@3.0.1

图片加载

const path = require('path')module.exports = {    entry:'./src/main.js',    output:{        path: path.resolve(__dirname,'dist'),        filename:'bundle.js',        publicPath: "dist/"    },    module: {        rules: [            {                test: /\.css$/,                use:['style-loader','css-loader']            },            {                test: /\.(png|jpg|gif|jpeg)$/,                use: [                    {                        loader: 'url-loader',                        options: {                            limit: 1024,                            name:"img/[name].[hash:8].[ext]"                        },                    },                ],            },        ]    }}
{  "name": "mett",  "version": "1.0.0",  "main": "webpack.config.js",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1",    "build": "webpack"  },  "author": "",  "license": "ISC",  "description": "",  "dependencies": {    "-": "0.0.1",    "D": "^1.0.0",    "build": "^0.1.4"  },  "devDependencies": {    "css-loader": "^2.0.2",    "file-loader": "^3.0.1",    "style-loader": "^0.23.1",    "url-loader": "^1.1.2",    "webpack": "^3.6.0"  }}

安装vue

npm install vue dev
 resolve:{        alias:{            'vue$':'vue/dist/vue.esm.js'        }    }

加载vue-loader

npm install vue-loader vue-template-compiler --save-dev

需要在webpack,config.js 的rules下面进行配置 (进行过滤)

package.json 每个配件的安装版本

版权插件

const path = require('path')const webpack = require('webpack')module.exports = {    entry:'./src/main.js',    output:{        path: path.resolve(__dirname,'dist'),        filename:'bundle.js',        publicPath: "dist/"    },    resolve:{        alias:{            'vue$':'vue/dist/vue.esm.js'        }    },    plugins: [        new webpack.BannerPlugin("最终版权归aa所有")            ],    module: {        rules: [            {                test: /\.css$/,                use:['style-loader','css-loader']            },            {                test: /\.vue$/,                use:['vue-loader']            },            {                test: /\.(png|jpg|gif|jpeg)$/,                use: [                    {                        loader: 'url-loader',                        options: {                            limit: 1024,                            name:"img/[name].[hash:8].[ext]"                        },                    },                ],            },        ]    }}

html打包插件

npm install html-webpack-plugin --save-dev
const path = require('path')const webpack = require('webpack')const HtmlWebpackPlugin = require('html-webpack-plugin')module.exports = {    entry:'./src/main.js',    output:{        path: path.resolve(__dirname,'dist'),        filename:'bundle.js',        publicPath: "dist/"    },    resolve:{        alias:{            'vue$':'vue/dist/vue.esm.js'        }    },    plugins: [        new webpack.BannerPlugin("最终版权归aa所有"),        new HtmlWebpackPlugin({            template:'index.html'        })    ],    module: {        rules: [            {                test: /\.css$/,                use:['style-loader','css-loader']            },            {                test: /\.vue$/,                use:['vue-loader']            },            {                test: /\.(png|jpg|gif|jpeg)$/,                use: [                    {                        loader: 'url-loader',                        options: {                            limit: 1024,                            name:"img/[name].[hash:8].[ext]"                        },                    },                ],            },        ]    }}

js 丑化插件

npm install uglifyjs-webpack-plugin@1.1.1 --save-dev
const path = require('path')const webpack = require('webpack')const HtmlWebpackPlugin = require('html-webpack-plugin')var uglifyjs = require('uglifyjs-webpack-plugin');module.exports = {    entry:'./src/main.js',    output:{        path: path.resolve(__dirname,'dist'),        filename:'bundle.js',        publicPath: "dist/"    },    resolve:{        alias:{            'vue$':'vue/dist/vue.esm.js'        }    },    plugins: [        new webpack.BannerPlugin("最终版权归aa所有"),        new HtmlWebpackPlugin({            template:'index.html'        }),        new uglifyjs()    ],    module: {        rules: [            {                test: /\.css$/,                use:['style-loader','css-loader']            },            {                test: /\.vue$/,                use:['vue-loader']            },            {                test: /\.(png|jpg|gif|jpeg)$/,                use: [                    {                        loader: 'url-loader',                        options: {                            limit: 1024,                            name:"img/[name].[hash:8].[ext]"                        },                    },                ],            },        ]    }}

搭建本地服务器

npm install webpack-dev-server@2.9.3 --save-dev
devServer: {        contentBase:'/dist',        inline:true }
webpack-dev-server

webpack配置文件分离合并

npm install webpack-merge --save-dev
{  "name": "mett",  "version": "1.0.0",  "main": "webpack.config.js",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1",    "build": "webpack --config ./build/prod.config.js",    "dev": "webpack-dev-server --open --config ./build/dev.config.js"  },  "author": "",  "license": "ISC",  "description": "",  "dependencies": {    "-": "0.0.1",    "D": "^1.0.0",    "build": "^0.1.4",    "requset": "0.0.1-security",    "vue": "^2.6.14"  },  "devDependencies": {    "css-loader": "^2.0.2",    "file-loader": "^3.0.1",    "html-webpack-plugin": "^3.0.0",    "style-loader": "^0.23.1",    "uglifyjs-webpack-plugin": "^1.1.1",    "url-loader": "^1.1.2",    "vue-loader": "^13.0.0",    "vue-template-compiler": "^2.6.14",    "webpack": "^3.6.0",    "webpack-dev-server": "^2.9.3",    "webpack-merge": "^3.0.0"  }}
const path = require('path')const webpack = require('webpack')const HtmlWebpackPlugin = require('html-webpack-plugin')module.exports = {    entry:'./src/main.js',    output:{        path: path.resolve(__dirname,'../dist'),        filename:'bundle.js',        // publicPath: "dist/"    },    resolve:{        extensions:['.js','.css','.vue'],        alias:{            'vue$':'vue/dist/vue.esm.js'        }    },    plugins: [        new webpack.BannerPlugin("最终版权归aa所有"),        new HtmlWebpackPlugin({            template:'index.html'        })    ],    module: {        rules: [            {                test: /\.css$/,                use:['style-loader','css-loader']            },            {                test: /\.vue$/,                use:['vue-loader']            },            {                test: /\.(png|jpg|gif|jpeg)$/,                use: [                    {                        loader: 'url-loader',                        options: {                            limit: 1024,                            name:"img/[name].[hash:8].[ext]"                        },                    },                ],            },        ]    }}
const webpackMerge = require('webpack-merge');const baseConfig = require('./base.config');module.exports =webpackMerge(baseConfig, {    devServer: {        contentBase:'dist/',        inline:true    }});
const webpackMerge = require('webpack-merge');const uglifyjs = require('uglifyjs-webpack-plugin')const baseConfig = require('./base.config');module.exports = webpackMerge(baseConfig,{    plugins: [        new uglifyjs()    ]});

脚手架CLI

需要 node >8.9

需要webpack

安装cli3

npm install -g @vue/cli

运行

vue create 项目
npm run serve

图形化

vue ui

安装 cli2

npm install -g @vue/cli-init -g

运行

vue init webpack 项目名称 

清理npm 缓存

npm cache clean --force

路由

URL的hash

我们可以通过直接赋值location.hash来改变href, 但是页面不发生刷新

history的pushState

​ history.pushState()

​ history.pushState({},’’,’/foo’)

​ history.back histort.go(-1)

​ histtory.forward histort.go(1)

动态路由

{      path:'/user/:userId',      component:user    },
    <router-link :to="'/user/'+userId"  replace >用户</router-link>
<template>  <div>    <h1>我是userdsadsadasdasfdsgdsfnedskfn</h1>    <p>哈哈哈</p>    <span>{{userId}}</span>  </div></template><script>    export default {        name: "user",        computed:{            userId(){                return this.$route.params.userId            }        }    }</script><style scoped></style>

嵌套路由

{      path:'/home',      component:home,      children:[        {          path:"/childIndex",          component:ChildIndex        }      ]    },

js懒加载

const home =()=> import('../components/Home')const about  =()=> import('../components/About')const user  =()=> import('../components/user')const ChildIndex  =()=> import('../components/ChildIndex')

参数传递

 <router-link :to="{path:'/childIndex',query:{name:'why',age:'18'}}">child</router-link>
      <span>{{$route.query.name+ $route.query.age}}</span>

参数传递2

 methods:{            btnClick(){                this.$router.push({                    path:'/home/childIndex',                    query: {                        name:"kkk",                        age:'22'                    }                })            }        }
 <button @click="btnClick">button2</button> 

create 函数

beforEach 函数 导航

router.beforeEach((to,from,next) =>{  document.title = to.matched[0].meta.title  next()})

生命周期

keep-alive

actived exclude

deactived

安装router

npm install vue-router --save

Promise

Vuex

状态管理模式,集中式存储管理

用户状态,用户名称,购物车,商品收藏

npm install vuex --save

store

import Vuex from 'vuex'import Vue from "vue";Vue.use(Vuex)const store = new Vuex.Store({  state:{    count:0  },  mutations:{    minus(state){      state.count--    },    plus(state){      state.count++    }  }});export default store
import Vue from 'vue'import App from './App'import router from './router'import store from "./store/store";Vue.config.productionTip = false/* eslint-disable no-new */new Vue({  el: '#app',  router,  store,  render: h => h(App)})
<template>  <div>    <h2>首页</h2>    <button @click="minus">-</button>    <p>{{count}}</p>    <button @click="plus">+</button>  </div></template><script>  export default {    name: "Home",    computed:{      count(){        return this.$store.state.count      }    },    methods:{       minus(){        this.$store.commit('minus');      },      plus(){        this.$store.commit('plus');      }    }  }</script><style scoped></style>

State 单一状态树

Getter

  • 计算属性
    <p>{{$store.getters.more20Student}}</p>    <p>{{$store.getters.moreStudent(22)}}</p>
  getters:{    more20Student(state){      return  state.student.filter(s => s.age >20)    },    moreStudent(state){      return age => {        return  state.student.filter(s => s.age 									>=age)      }    }  },

Mutation

添加對象,传递参数

 mutations:{    minus(state){      state.count--    },    plus(state){      state.count++    },    addStu(state,stud){      state.student.push(stud);    }  }
 methods:{      minus(){        this.$store.commit('minus');      },      plus(){        this.$store.commit('plus');      },      addStu(){        let stud = {id:"12330",name:"sadasd",age:111};        this.$store.commit("addStu",stud);      }    }

Action 异步

 actions:{    minus(context,payload){      return new Promise(resolve => {        context.commit('minus')        console.log("异步请求");        resolve("111")      })    }  }
 methods:{      minus(){        this.$store.dispatch('minus').then(          res =>{            console.log("里面完成了提交");            console.log(res)          }        );      },

Models分模块

axios 异步

安装

npm intall axios --save

并发

axios.all([axios({  url:"http://123.207.32.32:8000/home/multidata"}),axios({  url:"http://123.207.32.32:8000/home/data",  params:{    type:'sell',    page: 5  }})]).then(axios.spread((res1,res2) =>{  console.log(res1);  console.log(res2);}));
axios.all([axios({  url:"http://123.207.32.32:8000/home/multidata"}),axios({  url:"http://123.207.32.32:8000/home/multidata",  params:{    type:'sell',    page: 5  }})]).then(results =>{  console.log(results);})

封装

import axios from "axios";export function request(config){  const instance = axios.create({    baseURL:"http://123.207.32.32:8000",    timeout: 5000  })  return instance(config);}

请求拦截

import axios from "axios";export function request(config){  const instance = axios.create({    baseURL:"http://123.207.32.32:8000",    timeout: 5000  });  //拦截  instance.interceptors.request.use(config =>{      console.log(config);      return config;    },err => {      console.log(err)    }  );  instance.interceptors.response.use(res =>{      console.log(res);      return res;    },err => {      console.log(err)    }  );  return instance(config);}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

_Java123

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

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

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

打赏作者

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

抵扣说明:

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

余额充值