vue2 简单学习笔记

什么是 vue ?

  • Vue是一套构建用户界面的前端框架(现成的解决方案)
    • 构建用户界面:用vue往html页面中填充数据,非常的方便
    • 框架是一套现成的解决方案,程序员只能遵守框架的规范,去编写自己的业务功能

Vue的特性

  • vue框架的特性,主要体现在如下两方面:
    • 数据驱动视图
      • 在使用了vue的页面中,vue会监听数据的变化,从而自动重新渲染页面的结构。
      • 好处:当页面数据发生变化时,页面会自动重新渲染
      • 注意:数据驱动视图是单向的数据绑定
    • 双向数据绑定
      • 在填写表单时,双向数据绑定可以辅助开发者在不操作DOM的前提下,自动把用户填写的内容同步到数据源中。
      • 好处:开发者不再需要手动操作DOM元素,来获取表单元素最新的值!

MVVM(一种概念)

  • mvvmvue 实现数据驱动视图双向数据绑定的核心原理。MVVM 指的是 ModelViewViewModel 它把每个 HTML 页面都拆分成了三个部分。
    • Model:表示当前页面渲染时所依赖的数据源
    • View:表示当前页面所渲染的DOM结构
    • ViewModel:表示vue的实例,它是MVVM的核心
      • 是它把当前页面的数据源(model)和页面的结构(view)连接在了一起
      • 当数据源发生变化时,会被 ViewModel 监听到,ViewModel会根据最新的数据源自动更新页面的结构
      • 当表单元素的值发生变化时,也会被 ViewModel 监听到,ViewModel 会把变化过后最新的值自动同步到Model数据源中

vue/cli 脚手架

vue-cli 是什么?

  • vue-cli 是 Vue.js 开发的标准工具。它简化了程序员基于 webpack 创建工程化的 Vue 项目的过程。

vue-cli 的安装和使用

全局安装

  • vue-clinpm 上的一个全局包,使用 npm install 命令,即可方便的安装到自己的电脑上:
npm install -g @vue/cli

查看是否安装 vue-cli 方法

vue -V

创建 vue 脚手架项目

  • 通过 vue-cli 创建 vue 项目
vue create 项目名称

// 按需求可以选择如下配置:
Manually select features	// 回车

Babel	// 空格选中
Router	// 空格选中
Vuex // 空格选中
CSS Pre-peocessors	// 空格选中

2.x	 // 回车

Use history mode for router?  // 输入 n

Sass/SCSS	// 回车

In dedicated config files	// 回车

Save this as a preset for futurs projects? // n	回车

添加浏览器自启配置

  • vue.config.js 文件中配置浏览器自启等配置
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    open: true
  }
})

配置 @ 路径插件

  • 安装 path Autocomplete 插件
    在这里插入图片描述
  • VSCode 配置文件 settings.json 中添加如下配置:
"path-autocomplete.disableUpOneFolder": true,
  "path-autocomplete.pathMappings": {
    "@": "${folder}/src"
  },

vue 项目的运行流程

  • 在工程化的项目中,vue 要做的事情很单纯:通过 main.jsApp.vue 渲染到 index.html 的指定区域中。
    • App.vue:用来编写待渲染的模板结构
    • index.html:中需要预留一个el区域
    • main.jsApp.vue渲染到了index.html所预留的区域中

注册全局组件

  • 在 vue 项目的 main.js入口文件中,通过 Vue.component() 方法,可以注册全局组件。示例代码如下:
import About from '@/components/About'
// 参数1:字符串格式,表示组件的“注册名称”
// 参数2、需要被全局注册的那个组件
Vue.component('About',About)

常用数组方法

every函数

- 可用于检测当前数组中的每一个元素是否都符合某一条件。
- 返回值为布尔值。若全部符合条件,则返回真;若有一个元素不符合条件,则返回假。
- 不修改原数组
-	示例代码如下:
<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      arr: [
        { id: 1, name: "西瓜", state: true, price: 12, count: 3 },
        { id: 2, name: "黄瓜", state: false, price: 32, count: 4 },
        { id: 3, name: "葡萄", state: true, price: 65, count: 6 },
      ],
    };
  },
  created() {
    const result = this.arr.every((item) => item.state === true);
    console.log(result);  // 打印 false
  },
};
</script>

some 函数

  • 方法会依次执行数组的每个元素:
    • 如果有一个元素满足条件,则表达式返回 true , 剩余的元素不会再执行检测。
    • 如果没有满足条件的元素,则返回 false。
    • 示例代码如下:
<template>
  <div class="home">
    {{ name }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      arr: [
        { id: 1, name: "西瓜", state: true, price: 12, count: 3 },
        { id: 2, name: "黄瓜", state: true, price: 32, count: 4 },
        { id: 3, name: "葡萄", state: false, price: 65, count: 6 },
      ],
      name: "",
    };
  },
  created() {
    this.arr.some((item) => {
      if (item.name === "西瓜") {
        this.name = item.name;
        return;
      }
    });
  },
};
</script>

filter 函数

  • 创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
  • 示例代码如下:
<template>
  <div class="home">
    <ul>
      <li v-for="(item, index) in names" :key="index">{{ item }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      arr: [
        { id: 2, name: "黄瓜", state: true, price: 32, count: 4 },
        { id: 3, name: "葡萄", state: false, price: 65, count: 6 },
        { id: 1, name: "西瓜", state: true, price: 12, count: 3 },
      ],
      names: [],
    };
  },
  created() {
    this.names = this.arr.filter((item) => item.state);	// 返回 state = true 中的数组
  },
};
</script>

reduce 函数

  • 对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。语法为:
array.reduce(function(accumulator, currentValue, currentIndex, arr), initialValue);
/*
  accumulator:  必需。累计器
  currentValue: 必需。当前元素
  
  currentIndex: 可选。当前元素的索引;                    
  arr:          可选。要处理的数组
  initialValue: 可选。传递给函数的初始值,相当于accumulator的初始值
*/
  • 示例代码如下:
<template>
  <div>总金额:{{ priceCount }}</div>
</template>

<script>
export default {
  data() {
    return {
      arr: [
        { id: 1, name: "西瓜", state: true, price: 10, count: 3 },
        { id: 2, name: "黄瓜", state: false, price: 32, count: 4 },
        { id: 3, name: "葡萄", state: true, price: 10, count: 6 },
      ],
      priceCount: "",
    };
  },
  mounted() {
    //语法: reduce((累加的结果,当前循环想)=>{},0)
    const priceCount = this.arr
      .filter((item) => item.state)
      .reduce((amt, item) => {
        return (amt += item.price * item.count);
      }, 0);
    this.priceCount = priceCount;
  },
};
</script>

<style lang="less" scoped></style>

插槽

  • 插槽(Slot)是 vue 为组件的封装者提供的能力。允许开发者在封装组件时,把不确定的、希望由用户指定的部分定义为插槽。
  • 简单使用方法,示例代码如下:
<!-- 父组件 -->
<template>
  <HelloWorldVue :msg="'测试数据'">
    <template v-slot:CustomSlot> 自定义插槽 </template>
  </HelloWorldVue>
</template>

<script>
import HelloWorldVue from "@/components/HelloWorld.vue";
export default {
  components: {
    HelloWorldVue,
  },
  data() {
    return {
      
    };
  }
};
</script>

<style lang="less" scoped></style>
<!-- 子组件 -->
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <slot name="CustomSlot">
      <!-- 自定义插槽占位符 -->
    </slot>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: ["msg"],
};
</script>

<style scoped lang="scss"></style>

axios 网络请求

  • Axios 是一个基于 Promise 的网络请求库,可以用于浏览器和 node.js
  • Axios 使用简单,包尺寸小且提供了易于扩展的接口。

安装

npm install axios -S

全局挂载

  • main.js 文件中,示例代码如下:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'

// 设置公共请求地址
axios.defaults.baseURL = 'https://www.baidu.com'
// 全局挂载
Vue.prototype.$http = axios

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

请求拦截

  • main.js 文件中配置如下代码:
import axios from "axios";

// 配置默认请求地址
axios.defaults.baseURL = 'https://www.baidu.com'

// 配置请求拦截器
axios.interceptors.request.use(config => {
  // 为当前请求配置 Token 认证字段
  config.headers.Authorization = 'Bearer xxx'
  return config
})

Vue.prototype.$http = axios

响应拦截器

  • main.js 文件中添加如下代码:
import axios from "axios";

// 配置默认请求地址
axios.defaults.baseURL = 'https://www.baidu.com'

// 配置请求拦截器
axios.interceptors.request.use(config => {
  // 为当前请求配置 Token 认证字段
  config.headers.Authorization = 'Bearer xxx'
  return config
})

// 配置响应拦截器
axios.interceptors.response.use(function (response) {
  return response
}, function (error) {
  return Promise.reject(error)
})

Vue.prototype.$http = axios

配合 Element-ui 组件库添加全局 Loading 效果

  • 示例代码如下:
import axios from "axios";
import { Loading } from 'element-ui'

// 配置默认请求地址
axios.defaults.baseURL = 'https://www.baidu.com'

// Loading 状态
let loadingInstance = null

// 配置请求拦截器
axios.interceptors.request.use(config => {
  // 为当前请求配置 Token 认证字段
  config.headers.Authorization = 'Bearer xxx'
  // 添加 Loading ,开启 Loading
  loadingInstance = Loading.servece({ fullscreen: true })
  return config
})

// 配置响应拦截器
axios.interceptors.response.use(function (response) {
  // 关闭 Loading
  loadingInstance.close()
  return response
}, function (error) {
  return Promise.reject(error)
})

Vue.prototype.$http = axios

通过代理解决接口的跨域问题

  • 通过 vue-cli 创建的项目在遇到接口跨域问题时,可以通过代理的方式来解决;
    • 1、把 axios 的请求根路径设置为 vue 项目的运行地址(接口请求不再跨域)
    • 2、vue 项目发现请求的接口不存在,把请求转交给 proxy 代理
    • 3、代理把请求根路径替换为 devServer.proxy 属性的值,发起真正的数据请求
    • 4、代理把请求到的数据,转发给 axios
      在这里插入图片描述
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

W.Y.B.G

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

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

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

打赏作者

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

抵扣说明:

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

余额充值