Vue2 day07

1.vuex的基本认知

2.构建多组件共享的数据环境

步骤:

1.在自己创建的文件夹下创建脚手架

2.创建三个组件

### 源代码如下`App.vue`在入口组件中引入 Son1 和 Son2 这两个子组件```html
<template><div id="app"><h1>根组件</h1><input type="text"><Son1></Son1><hr><Son2></Son2></div>
</template><script>
import Son1 from './components/Son1.vue'
import Son2 from './components/Son2.vue'export default {name: 'app',data: function () {return {}},components: {Son1,Son2}
}
</script><style>
#app {width: 600px;margin: 20px auto;border: 3px solid #ccc;border-radius: 3px;padding: 10px;
}
</style>````main.js````js
import Vue from 'vue'
import App from './App.vue'Vue.config.productionTip = falsenew Vue({render: h => h(App)
}).$mount('#app')
````Son1.vue````html
<template><div class="box"><h2>Son1 子组件</h2>从vuex中获取的值: <label></label><br><button>值 + 1</button></div>
</template><script>
export default {name: 'Son1Com'
}
</script><style lang="css" scoped>
.box{border: 3px solid #ccc;width: 400px;padding: 10px;margin: 20px;
}
h2 {margin-top: 10px;
}
</style>````Son2.vue````html
<template><div class="box"><h2>Son2 子组件</h2>从vuex中获取的值:<label></label><br /><button>值 - 1</button></div>
</template><script>
export default {name: 'Son2Com'
}
</script><style lang="css" scoped>
.box {border: 3px solid #ccc;width: 400px;padding: 10px;margin: 20px;
}
h2 {margin-top: 10px;
}
</style>
```

整理好后目录如下:

运行结果

3.创建一个空仓库

1.安装veux

这里注意一下如果创建脚手架时有选择vuex选项就可以不要这一步了,这里是为了学习才没选,所以要安装

2.新建vuex模块文件

记得新建后要导出,然后在main.js中还要引用和挂载

使用的话就调用this.$store,像下图如果里面有的话就能输出来仓库里面的值。

4.如何提供&访问vuex的数据

eg:

mapState辅助函数

同理其他组件也可以这样访问仓库的值

修改vuex仓库的值

首先按下面这样写是不规范的,其次是要开启严格模式进行检查,才能检查出不规范的代码并且报错。

严格模式开启如下:

下面是修改步骤:

1.

2.

结果:

接下来就是把每个方法进行封装,按钮要干嘛就传什么参数

如果要多个参数传参,那么就要封装成obj对象

下面练习一下son2的减法操作:

5.辅助函数-mapMutations

6.核心概念-actions和getters

结果:

辅助函数方法:

7.vuex-分模块_模块创建

8.vuex-分模块_访问模块中的state&mutations等

原生访问方法:

基于模块的写法

为什么要像下面一样书写,因为该结构不一样

结构如下,所以就要像上面那样写

辅助函数写法

先介绍原生的:

然后写对应两种方法:

辅助函数

原生介绍:

先添加一个按钮

然后写点击事件的方法:

辅助函数:

9.购物车案例-功能分析-创建项目-构建基本结构

创建成功后将资料里面的src文件夹替换到创建完的文件夹里

10.购物车案例-构建购物车模块

步骤:

  1. 安装全局工具 json-server (全局工具仅需要安装一次)

yarn global add json-server 或 npm i json-server  -g
  1. 代码根目录新建一个 db 目录

  2. 将资料 index.json 移入 db 目录

  3. 进入 db 目录,执行命令,启动后端接口服务 (使用--watch 参数 可以实时监听 json 文件的修改)

json-server  --watch  index.json

要访问的话直接输入网址即可

然后在注意一下接口启动后是不能关的,一但关了就不能启动接口了。

11.购物车案例-请求获取数据存入vuex,映射渲染

1.安装 axios

yarn add axios

2.准备actions 和 mutations

import axios from 'axios'
​
export default {namespaced: true,state () {return {list: []}},mutations: {updateList (state, payload) {state.list = payload}},actions: {async getList (ctx) {const res = await axios.get('http://localhost:3000/cart')ctx.commit('updateList', res.data)}}
}

3.App.vue页面中调用 action, 获取数据

import { mapState } from 'vuex'
​
export default {name: 'App',components: {CartHeader,CartFooter,CartItem},created () {this.$store.dispatch('cart/getList')},computed: {...mapState('cart', ['list'])}
}

4.动态渲染

<!-- 商品 Item 项组件 -->
<cart-item v-for="item in list" :key="item.id" :item="item"></cart-item>

cart-item.vue

<template><div class="goods-container"><!-- 左侧图片区域 --><div class="left"><img :src="item.thumb" class="avatar" alt=""></div><!-- 右侧商品区域 --><div class="right"><!-- 标题 --><div class="title">{{ item.name }}</div><div class="info"><!-- 单价 --><span class="price">¥{{ item.price }}</span><div class="btns"><!-- 按钮区域 --><button class="btn btn-light" @click="btnClick(-1)">-</button><span class="count">{{ item.count }}</span><button class="btn btn-light" @click="btnClick(1)">+</button></div></div></div></div>
</template><script>
export default {name: 'CartItem',methods: {},props: {item: {type: Object,required: true}}
}</script>

12.购物车案例-修改数量和底部功能完成

  1. 注册点击事件

<!-- 按钮区域 -->
<button class="btn btn-light" @click="onBtnClick(-1)">-</button>
<span class="count">{{item.count}}</span>
<button class="btn btn-light" @click="onBtnClick(1)">+</button>

2.页面中dispatch action

onBtnClick (step) {const newCount = this.item.count + stepif (newCount < 1) return// 发送修改数量请求this.$store.dispatch('cart/updateCount', {id: this.item.id,count: newCount})
}

3.提供action函数

async updateCount (ctx, payload) {await axios.patch('http://localhost:3000/cart/' + payload.id, {count: payload.count})ctx.commit('updateCount', payload)
}

4.提供mutation处理函数

mutations: {...,updateCount (state, payload) {const goods = state.list.find((item) => item.id === payload.id)goods.count = payload.count}
},

  1. 提供getters

getters: {total(state) {return state.list.reduce((p, c) => p + c.count, 0);},totalPrice (state) {return state.list.reduce((p, c) => p + c.count * c.price, 0);},
},

2.动态渲染

<template><div class="footer-container"><!-- 中间的合计 --><div><span>共 {{total}} 件商品,合计:</span><span class="price">¥{{totalPrice}}</span></div><!-- 右侧结算按钮 --><button class="btn btn-success btn-settle">结算</button></div>
</template><script>
import { mapGetters } from 'vuex'
export default {name: 'CartFooter',computed: {...mapGetters('cart', ['total', 'totalPrice'])}
}
</script>

总的代码:

cart-footer.vue

<template><div class="footer-container"><!-- 中间的合计 --><div><span>共 {{ total }} 件商品,合计:</span><span class="price">¥{{ totalPrice }}</span></div><!-- 右侧结算按钮 --><button class="btn btn-success btn-settle">结算</button></div>
</template><script>
import { mapGetters } from 'vuex'
export default {name: 'CartFooter',computed: {...mapGetters('cart', ['total', 'totalPrice'])}
}
</script><style lang="less" scoped>
.footer-container {background-color: white;height: 50px;border-top: 1px solid #f8f8f8;display: flex;justify-content: flex-end;align-items: center;padding: 0 10px;position: fixed;bottom: 0;left: 0;width: 100%;z-index: 999;
}.price {color: red;font-size: 13px;font-weight: bold;margin-right: 10px;
}.btn-settle {height: 30px;min-width: 80px;margin-right: 20px;border-radius: 20px;background: #42b983;border: none;color: white;
}
</style>

cart-header.vue

<template><div class="header-container">购物车案例</div>
</template><script>
export default {name: 'CartHeader'
}
</script><style lang="less" scoped>
.header-container {height: 50px;line-height: 50px;font-size: 16px;background-color: #42b983;text-align: center;color: white;position: fixed;top: 0;left: 0;width: 100%;z-index: 999;
}
</style>

cart-item.vue

<template><div class="goods-container"><!-- 左侧图片区域 --><div class="left"><img :src="item.thumb" class="avatar" alt=""></div><!-- 右侧商品区域 --><div class="right"><!-- 标题 --><div class="title">{{ item.name }}</div><div class="info"><!-- 单价 --><span class="price">¥{{ item.price }}</span><div class="btns"><!-- 按钮区域 --><button class="btn btn-light" @click="btnClick(-1)">-</button><span class="count">{{ item.count }}</span><button class="btn btn-light" @click="btnClick(1)">+</button></div></div></div></div>
</template><script>
export default {name: 'CartItem',methods: {btnClick (step) {const newCount = this.item.count + stepconst id = this.item.idif (newCount < 1) returnthis.$store.dispatch('cart/updateCountAsync', {id,newCount})}},props: {item: {type: Object,required: true}}
}
</script><style lang="less" scoped>
.goods-container {display: flex;padding: 10px;+ .goods-container {border-top: 1px solid #f8f8f8;}.left {.avatar {width: 100px;height: 100px;}margin-right: 10px;}.right {display: flex;flex-direction: column;justify-content: space-between;flex: 1;.title {font-weight: bold;}.info {display: flex;justify-content: space-between;align-items: center;.price {color: red;font-weight: bold;}.btns {.count {display: inline-block;width: 30px;text-align: center;}}}}
}.custom-control-label::before,
.custom-control-label::after {top: 3.6rem;
}
</style>

cart.js

import axios from 'axios'
export default {namespaced: true,state () {return {// 购物车数据 [{}, {}]list: []}},mutations: {updateList (state, newList) {state.list = newList},// obj: { id: xxx, newCount: xxx }updateCount (state, obj) {// 根据 id 找到对应的对象,更新count属性即可const goods = state.list.find(item => item.id === obj.id)goods.count = obj.newCount}},actions: {// 请求方式:get// 请求地址:http://localhost:3000/cartasync getList (context) {const res = await axios.get('http://localhost:3000/cart')context.commit('updateList', res.data)},// 请求方式:patch// 请求地址:http://localhost:3000/cart/:id值  表示修改的是哪个对象// 请求参数:// {//   name: '新值',  【可选】//   price: '新值', 【可选】//   count: '新值', 【可选】//   thumb: '新值'  【可选】// }async updateCountAsync (context, obj) {// 将修改更新同步到后台服务器await axios.patch(`http://localhost:3000/cart/${obj.id}`, {count: obj.newCount})// 将修改更新同步到 vuexcontext.commit('updateCount', {id: obj.id,newCount: obj.newCount})}},getters: {// 商品总数量 累加counttotal (state) {return state.list.reduce((sum, item) => sum + item.count, 0)},// 商品总价格 累加count * pricetotalPrice (state) {return state.list.reduce((sum, item) => sum + item.count * item.price, 0)}}
}

index.js

import Vue from 'vue'
import Vuex from 'vuex'
import cart from './modules/cart'
Vue.use(Vuex)export default new Vuex.Store({modules: {cart}
})

App.vue

<template><div class="app-container"><!-- Header 区域 --><cart-header></cart-header><!-- 商品 Item 项组件 --><cart-item v-for="item in list" :key="item.id" :item="item"></cart-item><!-- Foote 区域 --><cart-footer></cart-footer></div>
</template><script>
import CartHeader from '@/components/cart-header.vue'
import CartFooter from '@/components/cart-footer.vue'
import CartItem from '@/components/cart-item.vue'
import { mapState } from 'vuex'export default {name: 'App',created () {this.$store.dispatch('cart/getList')},components: {CartHeader,CartFooter,CartItem},computed: {...mapState('cart', ['list'])}
}
</script><style lang="less" scoped>
.app-container {padding: 50px 0;font-size: 14px;
}
</style>

main.js

import Vue from 'vue'
import App from './App.vue'
import store from './store'Vue.config.productionTip = falsenew Vue({store,render: h => h(App)
}).$mount('#app')

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/news/913386.shtml
繁体地址,请注明出处:http://hk.pswp.cn/news/913386.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

简述MCP的原理-AI时代的USB接口

1 简介随着AI的不断发展&#xff0c;RAG&#xff08;检索增强生成&#xff09;和function calling等技术的出现&#xff0c;使得大语言模型的对话生成能力得到了增强。然而&#xff0c;function calling的实现逻辑比较复杂&#xff0c;一个简单的工具调用和实现方式需要针对不同…

CISSP知识点汇总-资产安全

CISSP知识点汇总 域1---安全与风险管理域2---资产安全域3---安全工程域4---通信与网络安全域5---访问控制域6---安全评估与测试域7---安全运营域8---应用安全开发域2 资产安全 一、资产识别和分类 1、信息分级(Classification): 按照敏感程度(机密性被破坏) 按照重要程度…

Spring Boot 3.x 整合 Swagger(springdoc-openapi)实现接口文档

本文介绍 Spring Boot 3.x 如何使用 springdoc-openapi 实现 Swagger 接口文档&#xff0c;包括版本兼容表、最简单的配置示例和常见错误解决方案。1. Spring Boot 3.x 和 springdoc-openapi 版本对应表Spring Boot 版本Spring Framework 版本推荐的 springdoc-openapi 版本3.0…

Redis内存队列Stream

本文为个人学习笔记整理&#xff0c;仅供交流参考&#xff0c;非专业教学资料&#xff0c;内容请自行甄别 文章目录概述一、生产者端操作二、消费者端操作三、消费组操作四、状态查询操作五、确认消息六、消息队列的选择概述 Stream是Redis5.0推出的支持多播的可持久化的消息队…

Minio安装配置,桶权限设置,nginx代理 https minio

**起因&#xff1a;因为用到ruoyi-vue-plus框架中遇到生产环境是https&#xff0c;但是http的minio上传的文件不能在后台系统中访问**安装配置minio1. 下载安装2. 赋文件执行权限3.创建配置文件4.创建minio.service新版minio创建桶需要配置桶权限1.下载客户端2.设置访问权限3.连…

数论基础知识和模板

质数筛 用于快速处理 1&#xff5e;n 中所有素数的算法 因为依次遍历判断每一个数是否质数太慢&#xff0c;所以把一些明显不能质数的筛出来 普通筛法&#xff0c;对于每个整数&#xff0c;删除掉其倍数。 bool vis[N];//0表示是质数 int pri[N],o; //质数表 void get(int n…

Ubuntu20.04.6桌面版系统盘制作与安装

概述 本教程讲述Ubuntu20.04.6桌面版的系统U盘制作与安装&#xff0c;所需工具为一台电脑、大于4G的U盘、一个需要安装Ubuntu系统的主机。 步骤1&#xff1a;下载系统镜像与rufus 在ubuntu官网下载 ubuntu-20.04.6-desktop-amd64.iso&#xff0c;如图 下载rufus工具&#xf…

【C++复习3】类和对象

1.3.1.简述一下什么是面向对象回答&#xff1a;1. 面向对象是一种编程思想&#xff0c;把一切东西看成是一个个对象&#xff0c;比如人、耳机、鼠标、水杯等&#xff0c;他们各 自都有属性&#xff0c;比如&#xff1a;耳机是白色的&#xff0c;鼠标是黑色的&#xff0c;水杯是…

数据结构之二叉平衡树

系列文章目录 数据结构之ArrayList_arraylist o(1) o(n)-CSDN博客 数据结构之LinkedList-CSDN博客 数据结构之栈_栈有什么方法-CSDN博客 数据结构之队列-CSDN博客 数据结构之二叉树-CSDN博客 数据结构之优先级队列-CSDN博客 常见的排序方法-CSDN博客 数据结构之Map和Se…

Maven引入第三方JAR包实战指南

要将第三方提供的 JAR 包引入本地 Maven 仓库&#xff0c;可通过以下步骤实现&#xff08;以 Oracle JDBC 驱动为例&#xff09;&#xff1a;&#x1f527; 方法 1&#xff1a;使用 install:install-file 命令&#xff08;推荐&#xff09;定位 JAR 文件 将第三方 JAR 包&#…

JavaSE -- 泛型详细介绍

泛型 简介 集合存储数据底层是利用 Object 来接收的&#xff0c;意思是说如果不对类型加以限制&#xff0c;所有数据类型柔和在一起&#xff0c;这时如何保证数据的安全性呢&#xff08;如果不限制存入的数据类型&#xff0c;任何数据都能存入&#xff0c;当我们取出数据进行强…

使用 Python 实现 ETL 流程:从文本文件提取到数据处理的全面指南

文章大纲&#xff1a; 引言&#xff1a;什么是 ETL 以及其重要性 ETL&#xff08;提取-转换-加载&#xff09;是数据处理领域中的核心概念&#xff0c;代表了从源数据到目标系统的三个关键步骤&#xff1a;**提取&#xff08;Extract&#xff09;**数据、**转换&#xff08;Tra…

selenium基础知识 和 模拟登录selenium版本

前言 selenium框架是Python用于控制浏览器的技术,在Python爬虫获取页面源代码的时候,是最重要的技术之一,通过控制浏览器,更加灵活便捷的获取浏览器中网页的源代码。 还没有安装启动selenium的同志请先看我的上一篇文章进行配置启动 和 XPath基础 对selenium进行浏览器和驱动…

JS 网页全自动翻译v3.17发布,全面接入 GiteeAI 大模型翻译及自动部署

两行 js 实现 html 全自动翻译。 无需改动页面、无语言配置文件、无 API Key、对 SEO 友好&#xff01; 升级说明 translate.service 深度绑定 GiteeAI 作为公有云翻译大模型算力支持translate.service 增加shell一键部署后通过访问自助完成GiteeAI的开通及整个接入流程。增加…

数据结构:数组:插入操作(Insert)与删除操作(Delete)

目录 插入操作&#xff08;Inserting in an Array&#xff09; 在纸上模拟你会怎么做&#xff1f; 代码实现 复杂度分析 删除操作&#xff08;Deleting from an Array&#xff09; 在纸上模拟一下怎么做&#xff1f; 代码实现 复杂度分析 插入操作&#xff08;Inserti…

Qt之修改纯色图片的颜色

这里以修改QMenu图标颜色为例,效果如下: MyMenu.h #ifndef MYMENU_H #define MYMENU_H#include <QMenu>class MyMenu : public QMenu { public:explicit MyMenu(QWidget *parent = nullptr);protected:void mouseMoveEvent(QMouseEvent *event) override; };#endif /…

uni-app实现单选,多选也能搜索,勾选,选择,回显

前往插件市场安装插件下拉搜索选择框 - DCloud 插件市场&#xff0c;该插件示例代码有vue2和vue3代码 是支持微信小程序和app的 示例代码&#xff1a; <template><view><!-- 基础用法 --><cuihai-select-search:options"options"v-model&quo…

【机器学习深度学习】 微调的十种形式全解析

目录 一、为什么要微调&#xff1f; 二、微调的 10 种主流方式 ✅ 1. 全参数微调&#xff08;Full Fine-tuning&#xff09; ✅ 2. 冻结部分层微调&#xff08;Partial Fine-tuning&#xff09; ✅ 3. 参数高效微调&#xff08;PEFT&#xff09; &#x1f538; 3.1 LoRA&…

信刻光盘安全隔离与文件单向导入/导出系统

北京英特信网络科技有限公司成立于2005年&#xff0c;是专业的数据光盘摆渡、刻录分发及光盘存储备份领域的科技企业&#xff0c;专注为军队、军工、司法、保密等行业提供数据光盘安全摆渡、跨网交换、档案归档检测等专业解决方案。 公司立足信创产业&#xff0c;产品国产安全可…

Python-标准库-os

1 需求 2 接口 3 示例 4 参考资料 在 Python 中&#xff0c;os&#xff08;Operating System&#xff09;模块是一个非常重要的内置标准库&#xff0c;提供了许多与操作系统进行交互的函数和方法&#xff0c;允许开发者在 Python 程序中执行常见的操作系统任务&#xff0c;像文…