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
英文地址,請注明出處:http://en.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;像文…