Vue 学习笔记4(77-87)

Vue 学习笔记4(77-87)

学习地址:https://ke.qq.com/course/279700

目录:

  • 01-01 git下载代码
  • 02-27 Vue2.x
  • 28-39 路由精讲
  • 40-49 Vue-Cli3.0
  • 50-64 Vue2.x-实战项目(个人博客)
  • 65-76 Vue2.x-实战项目(用户管理)
  • 77-87 Vuex 核心概念如下

vuex

01 Vuex-成果展示及项目搭建

02 Vuex-一个简单的Vue APP

父子传值

<product-list-one :products='products'></product-list-one>
props: ['products'],

State

03 Vuex-搭建Vuex中央状态管理, 04 Vuex-使用computed获取store数据

Vuex

Centralized State Management for Vue.js.

src 目录下新建 store 文件夹,下面新建 index.js 文件

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const store = new Vuex.Store({
  state:{
    products:[
      {name:'马云',price:'200'},
      {name:'马化腾',price:'140'},
      {name:'马冬梅',price:'20'},
      {name:'马蓉',price:'10'},
    ]
  }
}) 

main.js 中引入

import {store} from './store'
new Vue({
  store,
  ...
}

组建中使用,computed 属性获取 store 中数据

<li v-for="product in products" :key='product'>
  <span class="name">{{product.name}}</span>
  <span class="price">${{product.price}}</span>
</li>

<script>
export default{
  computed: {
    products(){
      return this.$store.state.products
    }
  },
}
</script>

Getter

05 Vuex-Getters

index.js 文件中,新增 getters 属性,里面放其他组件可以调用的方法

export const store = new Vuex.Store({
  state:{
    products:[
      {name:'马云',price:'200'},
      {name:'马化腾',price:'140'},
      {name:'马冬梅',price:'20'},
      {name:'马蓉',price:'10'},
    ]
  },
  getters:{
    saleProducts:(state)=>{
      var saleProducts = state.products.map(product =>{
        return{
          name: "**" + product.name + "**" ,
          price: product.price / 2
        }
      });
      return saleProducts;
    }
  }
}) 

组件对 store 中方法的调用

<li v-for="product in saleProducts" :key='product'>
  <span class="name">{{product.name}}</span>
  <span class="price">${{product.price}}</span>
</li>

<script>
export default{
  computed: {
    saleProducts(){
      return this.$store.getters.saleProducts;
    }
  },
}
</script>

Mutation

06 Vuex-Mutations

谷歌浏览器添加插件Vue.js devtools可以跟踪vuex状态

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数。

store/index.js 中添加 mutations 属性

  mutations:{
    reducePriceV:state=>{
      state.products.forEach(product =>{
        product.price -= 1;
      })
    }
  }

组建中调用方法 reducePriceV

<button @click="reducePrice">降价</button>
<script>
export default {
  methods: {
    reducePrice(){
      this.$store.commit('reducePriceM') // mutations中的方法
    }
  },
}
</script>

Action

07 Vuex-Actions

Action 类似于 mutation,不同在于:

  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。(vuex调试器中方法和变化同时出来)

注册action

Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.statecontext.getters 来获取 state 和 getters。

组件触发action

Action 通过 store.dispatch 方法触发

接收第二个参数 payload

eg:

store/index.js 中添加 actions 属性

  actions:{
    reducePriceA:context=>{
      setTimeout(function(){
        context.commit('reducePriceM')
      },2000)
    }
  }

组建中调用方法 reducePriceM

<button @click="reducePrice">降价</button>
<script>
export default {
  methods: {
    reducePrice(){
      this.$store.dispatch('reducePriceA') // actions中的方法
    }
  },
}
</script>

08 Vuex-mapMutations & mapActions

在组件中提交 Mutation

你可以在组件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)。

import { mapMutations } from 'vuex'

export default {
  // ...
  methods: {
    ...mapMutations([
      'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`

      // `mapMutations` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
    ]),
    ...mapMutations({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
  }
}

在组件中分发 Action

你在组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store):

import { mapActions } from 'vuex'

export default {
  // ...
  methods: {
    ...mapActions([
      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

      // `mapActions` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })
  }
}

Module

09 Vuex-Module

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: { ... },
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 223,426评论 6 521
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 95,567评论 3 401
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 170,342评论 0 366
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 60,420评论 1 300
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 69,424评论 6 398
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,964评论 1 314
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 41,365评论 3 426
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 40,330评论 0 278
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,862评论 1 322
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,921评论 3 343
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 41,063评论 1 354
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,717评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 42,393评论 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,880评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 34,002评论 1 275
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 49,540评论 3 380
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 46,084评论 2 361

推荐阅读更多精彩内容