Vuex中的核心特性

1.Vuex概述

之前组件之间共享数据的方式

1609209205399

Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间的数据共享

1609208271824

使用Vuex管理数据的好处:

A.能够在vuex中集中管理共享的数据,便于开发和后期进行维护

B.能够高效的实现组件之间的数据共享,提高开发效率

C.存储在vuex中的数据是响应式的,当数据发生改变时,页面中的数据也会同步更新

什么样的数据适合存储到Vuex中

一般情况下,只有组件之间共享的数据,才有必要存储到vuex中;对于组件中的私有数据,依旧存储在组件自身的data中即可

2.Vuex的基本使用

1609209555886

1609209564325

创建带有vuex的vue项目,打开终端,输入命令:vue ui

当项目仪表盘打开之后,我们点击页面左上角的项目管理下拉列表,再点击Vue项目管理器

点击创建项目,如下图所示

第一步,设置项目名称和包管理器


第二步,设置手动配置项目

第三步,设置功能项


第四步,创建项目

在项目结构中:

store/index.js中,安装vuex,导入vuex并安装到vue项目中,然后new Vuex的实例对象,并且暴露出去,其中state参数用于存放共享的数据

1609209335045

在main.js中,在new Vue对象期间将创建出来的 store 挂载到Vue实例中

1609209524233

3.使用Vuex完成计数器案例

打开刚刚创建的vuex项目,找到src目录中的App.vue组件,将代码重新编写如下:

<template>
  <div>
    <my-addition></my-addition>

    <p>----------------------------------------</p>

    <my-subtraction></my-subtraction>
  </div>
</template>

<script>
import Addition from './components/Addition.vue'
import Subtraction from './components/Subtraction.vue'

export default {
  data() {
    return {}
  },
  components: {
    'my-subtraction': Subtraction,
    'my-addition': Addition
  }
}
</script>

<style>
</style>

在components文件夹中创建Addition.vue组件,代码如下:

<template>
    <div>
        <h3>当前最新的count值为:</h3>
        <button>+1</button>
    </div>
</template>

<script>
export default {
  data() {
    return {}
  }
}
</script>

<style>
</style>

在components文件夹中创建Subtraction.vue组件,代码如下:

<template>
    <div>
        <h3>当前最新的count值为:</h3>
        <button>-1</button>
    </div>
</template>

<script>
export default {
  data() {
    return {}
  }
}
</script>

<style>
</style>

最后在项目根目录(与src平级)中创建 .prettierrc 文件,编写代码如下:

{
    "semi":false,
    "singleQuote":true
}

4.Vuex中的核心特性

A.State

​ State提供唯一的公共数据源,所有共享的数据都要统一放到Store中的State中存储

​ 例如,打开项目中的store.js文件,在State对象中可以添加我们要共享的数据,如:count:0

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})

在组件中访问State的方式:

1).this.$store.state.全局数据名称  如:this.$store.state.count

2).先按需导入mapState函数: import { mapState } from 'vuex'
然后数据映射为计算属性: computed:{ ...mapState(['全局数据名称']) }

方式一:

<template>
  <div>
    <h3>当前最新的count值为: {{$store.state.count}}</h3>
    <button>+1</button>
  </div>
</template>

<script>
export default {
  data() {
    return {

    }
  }
}
</script>

方式二:

<template>
  <div>
    <h3>当前最新的count值为:{{count}}</h3>
    <button>-1</button>
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  data() {
    return {}
  },
  computed: {
    // 通过展开运算符,把vuex中全局的属性映射为当前组件的一个计算属性
    ...mapState(['count'])
  }
}
</script>

<style>
</style>

B.Mutation

Mutation用于修改变更$store中的数据

① 只能通过 mutation 变更 Store 数据,不可以直接操作 Store 中的数据

② 通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化。

1609211695570

可以在触发 mutations 时传递参数:

1609211814379

使用方式:

打开store.js文件,在mutations中添加代码如下

mutations: {
    add(state,step){
      //第一个形参永远都是state也就是$state对象
      //第二个形参是调用add时传递的参数
      state.count+=step;
    }
  }

然后在Addition.vue中给按钮添加事件代码如下:

<button @click="btnHander2">+N</button>
methods:{
  btnHander2() {
    //使用commit函数调用mutations中的对应函数,
    //第一个参数就是我们要调用的mutations中的函数名
    //第二个参数就是传递给add函数的参数
    this.$store.commit('add',10)
  }
}

this.$store.commit() 是触发 mutations 的第一种方式,触发 mutations 的第二种方式:

// 1. 从 vuex 中按需导入 mapMutations 函数
import { mapMutations } from 'vuex'

通过刚才导入的 mapMutations 函数,将需要的 mutations 函数,映射为当前组件的 methods 方法:

// 2. 将指定的 mutations 函数,映射为当前组件的 methods 函数
methods: {
	...mapMutations(['add', 'addN'])
}

如下:

import { mapState,mapMutations } from 'vuex'

export default {
  data() {
    return {}
  },
  methods:{
      //获得mapMutations映射的sub函数
      ...mapMutations(['sub']),
      //当点击按钮时触发Sub函数
      Sub(){
          //调用sub函数完成对数据的操作
          this.sub(10);
      }
  },
  computed:{
      ...mapState(['count'])
      
  }
}

C.Action

在mutations中不能编写异步的代码,会导致vue调试器的显示出错。

在vuex中我们可以使用Action来执行异步操作。

如果通过异步操作变更数据,必须通过 Action,而不能使用 Mutation,但是在 Action 中还是要通过触发
Mutation 的方式间接变更数据。

1609213943417

在store.js中:

......
actions: {
    addAsync(context) {
      setTimeout(() => {
        // 在action中,不能直接修改state中的数据
        // 必须通过 context.commit() 触发某个 mutations 才行
        context.commit('add')
      }, 1000)
    }
  },
......

在Addition.vue中:

<button @click="btnHander3">+1 Async</button>
 methods: {
    ......
    // 异步地让 count 自增 +1
    btnHander3() {
      // 这里的 dispatch 函数,专门用来触发action
      this.$store.dispatch('addAsync')
    }
  }

触发 actions 异步任务时携带参数:

1609214141421

操作步骤如下:

打开store.js文件,修改Action,如下:

actions: {
  addNAsync(context, step){
    setTimeout(() => {
      // 在action中,不能直接修改state中的数据
      // 必须通过 context.commit() 触发某个 mutations 才行  
      context.commit('add',step);
    },1000)
  }
}

然后在Addition.vue中给按钮添加事件代码如下:

<button @click="btnHander4">+N Async</button>
methods:{
  	// 异步地让 count 自增N (携带参数)
    btnHander4() {
      // 这里的 dispatch 函数,专门用来触发action
      this.$store.dispatch('addNAsync', 5)
    }
}

第二种方式:

this.$store.dispatch() 是触发 actions 的第一种方式,触发 actions 的第二种方式:

// 1. 从 vuex 中按需导入 mapActions 函数
import { mapActions } from 'vuex'

通过刚才导入的 mapActions 函数,将需要的 actions 函数,映射为当前组件的 methods 方法:

// 2. 将指定的 actions 函数,映射为当前组件的 methods 函数
methods: {
	...mapActions(['addASync', 'addNASync'])
}

如下:

在store.js定义actions

actions: {
    ......
    subAsync(context) {
      setTimeout(() => {
        context.commit('sub')
      }, 1000)
    },
    subNAsync(context, step) {
      setTimeout(() => {
        context.commit('subN', step)
      }, 1000)
    }
  },

在Subtraction.vue中:

相较于之前的简化操作:

这里绑定事件函数可以直接使用映射过来的函数,不需要再自己重新定义事件处理函数

<template>
  <div>
    <h3>当前最新的count值为:{{count}}</h3>
    <button @click="sub">-1</button>
    <button @click="subN(3)">-N</button>
    <button @click="subAsync">-1 Async</button>
    <button @click="subNAsync(5)">-N Async</button>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from 'vuex'

export default {
  data() {
    return {}
  },
  computed: {
    // 通过展开运算符,把vuex中全局的属性映射为当前组件的一个计算属性
    ...mapState(['count'])
  },
  methods: {
    ...mapMutations(['sub', 'subN']),
    // 这里本质上是把全局的某个函数映射到自己methods中的函数,
    // 所以可以直接将其绑定到点击事件上作为时间处理函数
    ...mapActions(['subAsync', 'subNAsync'])
  }
}
</script>

<style>
</style>

D.Getter

Getter用于对Store中的数据进行加工处理形成新的数据

① Getter 可以对 Store 中已有的数据加工处理之后形成新的数据,类似 Vue 的计算属性。

② Store 中数据发生变化, Getter 的数据也会跟着变化。

它只会包装Store中保存的数据,并不会修改Store中保存的数据,当Store中的数据发生变化时,Getter生成的内

容也会随之变化

1609222887933

打开store.js文件,添加getters,如下:

export default new Vuex.Store({
  .......
  //添加了一个showNum的属性
  getters: {
    showNum(state) {
      return '当前最新的数量是【' + state.count + '】'
    }
  },
})

使用 getters 的第一种方式:

this.$store.getters.名称  

使用 getters 的第二种方式:

import { mapGetters } from 'vuex'

computed: {
	...mapGetters(['showNum'])
}

然后打开Addition.vue中,添加插值表达式使用getters (第一种方式)

<h3>{{$store.getters.showNum}}</h3>

在Addition.vue中,导入mapGetters,并将之映射为计算属性 (第二种方式)

<h3>{{showNum}}</h3>
import { mapGetters } from 'vuex'

computed: {
    // 通过展开运算符,把vuex中全局的属性映射为当前组件的一个计算属性
    ......
    ...mapGetters(['showNum'])
  },

5.vuex案例

展示效果:

1609234482932

具体功能步骤:

① 动态加载任务列表数据
② 实现文本框与store数据的双向同步
③ 完成添加任务事项的操作
④ 完成删除任务事项的操作
⑤ 动态绑定复选框的选中状态
⑥ 修改任务事项的完成状态
⑦ 统计未完成的任务的条数
⑧ 清除已完成的任务事项
⑨ 实现任务列表数据的动态切换

A.初始化案例

① 通过 vue ui 命令打开可视化面板,创建新项目 vuex-demo2

② 安装 vuex 依赖包 npm install vuex axios ant-design-vue –S

③ 实现 Todos 基本布局(基于已有样式模板)

首先使用vue ui初始化一个使用vuex的案例

然后打开public文件夹,创建一个list.json文件,文件代码如下:

[
    {
        "id": 0,
        "info": "Racing car sprays burning fuel into crowd.",
        "done": false
    },
    {
        "id": 1,
        "info": "Japanese princess to wed commoner.",
        "done": false
    },
    {
        "id": 2,
        "info": "Australian walks 100km after outback crash.",
        "done": false
    },
    {
        "id": 3,
        "info": "Man charged over missing wedding girl.",
        "done": false
    },
    {
        "id": 4,
        "info": "Los Angeles battles huge wildfires.",
        "done": false
    }
]

再接着,打开main.js,添加store.js的引入,如下:

import Vue from 'vue'
import App from './App.vue'
import store from './store.js'

// 1. 导入 ant-design-vue 组件库
import Antd from 'ant-design-vue'
// 2. 导入组件库的样式表
import 'ant-design-vue/dist/antd.css'

Vue.config.productionTip = false
// 3. 安装组件库
Vue.use(Antd)

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

再接着打开store.js,添加axios请求json文件获取数据的代码,如下:

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    //所有任务列表
    list: [],
    //文本输入框中的值
    inputValue: 'AAA'
  },
  mutations: {
    initList(state, list) {
      // 需要动态的为list重新赋值
      // 只能通过mutations来操作state中的数据列表,然后再actions中调用对应的mutations来为list重新赋值
      state.list = list
    },
    setInputValue(state,value){
      state.inputValue = value
    }
  },
  actions: {
    // axios发起请求是一个异步操作,所以需要定义到actions中
    getList(context) {
      axios.get('/list.json').then(({ data }) => {
        console.log(data);
        // 调用mutations中的initList为list赋值,并传递参数
        context.commit('initList', data)
      })
    }
  }
})

最后,代开App.vue文件,将store中的数据获取并展示:

<template>
  <div id="app">
    <a-input placeholder="请输入任务" class="my_ipt" :value="inputValue" @change="handleInputChange" />
    <a-button type="primary">添加事项</a-button>

    <a-list bordered :dataSource="list" class="dt_list">
      <a-list-item slot="renderItem" slot-scope="item">
        <!-- 复选框 -->
        <a-checkbox :checked="item.done">{{item.info}}</a-checkbox>
        <!-- 删除链接 -->
        <a slot="actions">删除</a>
      </a-list-item>

      <!-- footer区域 -->
      <div slot="footer" class="footer">
        <!-- 未完成的任务个数 -->
        <span>0条剩余</span>
        <!-- 操作按钮 -->
        <a-button-group>
          <a-button type="primary">全部</a-button>
          <a-button>未完成</a-button>
          <a-button>已完成</a-button>
        </a-button-group>
        <!-- 把已经完成的任务清空 -->
        <a>清除已完成</a>
      </div>
    </a-list>
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: 'app',
  data() {
    return {
      // list:[]
    }
  },
  created(){
    // console.log(this.$store);
    // dispatch方法来触发actions
    this.$store.dispatch('getList')
  },
  methods:{
    // 监听文本框内容变化
    handleInputChange(e){
      // 文本框发生变化拿到一个事件参数e
      // console.log(e.target.value)
      // 动态修改store中全局inputValue属性的值
      this.$store.commit('setInputValue',e.target.value)
    }
  },
  computed:{
    // 将store中的全局的state数据映射为当前组件的一个计算属性
    ...mapState(['list','inputValue'])
  }
}
</script>

<style scoped>
#app {
  padding: 10px;
}

.my_ipt {
  width: 500px;
  margin-right: 10px;
}

.dt_list {
  width: 500px;
  margin-top: 10px;
}

.footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

B.完成添加事项

首先,打开App.vue文件,给“添加事项”按钮绑定点击事件,编写处理函数

//绑定事件
<a-button type="primary" @click="addItemToList">添加事项</a-button>

//编写事件处理函数
methods:{
    ......
    // 向列表中新增item项
    addItemToList(){
      //向列表中新增事项
      if(this.inputValue.trim().length <= 0){
        // $message.warning是导入的ant-design组件ui库提供的
        // 会自动向每个组件的this上绑定$message
        return this.$message.warning('文本框内容不能为空')
      }
	  // 调用mutations中的addItem向list中新增item项
      this.$store.commit('addItem')
    }
  }

然后打开store.js编写addItem

export default new Vuex.Store({
  state: {
    //所有任务列表
    list: [],
    //文本输入框中的值
    inputValue: 'AAA',
    //下一个id(因为这是个纯前端项目,所以id我们自己定义)
    nextId:5
  },
  mutations: {
    ........
    //添加列表项
    addItem(state){
      const obj = {
        id: state.nextId,
        info: state.inputValue.trim(),
        done: false
      }
      //将创建好的事项添加到数组list中
      state.list.push(obj)
      //将nextId值自增
      state.nextId++
	  // 将文本框内容清空
      state.inputValue = ''
    }
  }
  ......
})


C.完成删除事项

首先,打开App.vue文件,给“删除”按钮绑定点击事件,编写处理函数

//绑定事件
<a slot="actions" @click="removeItemById(item.id)">删除</a>
//编写事件处理函数
methods:{
    ......
    removeItemById(id){
      //根据id删除事项
      this.$store.commit('removeItem',id)
    }
  }

然后打开store.js编写addItem

export default new Vuex.Store({
  ......
  mutations: {
    ........
    //根据id删除事项数据
    removeItem(state,id){
      // 根据id查找对应项的索引
      const index = state.list.findIndex( x => x.id === id )
	  // 根据索引删除对应的元素
      // console.log(index);
      if (i !== -1) {
        // 从索引i开始,删除1项
        state.list.splice(i, 1)
      }
    }
  }
  ......
})

D.完成选中状态的改变

首先,打开App.vue文件,给“复选”按钮绑定点击事件,编写处理函数

//绑定事件
<a-checkbox :checked="item.done" @change="cbStatusChanged(item.id,$event)">{{item.info}}</a-checkbox>

//编写事件处理函数
methods:{
    ......
    // 监听复选框选中状态变化的事件
    cbStatusChanged(id,e){
      // 通过e.target.checked可以接收到最新的选中状态
      // console.log(e.target.checked)
      // console.log(id)
      // 组织一个参数对象
      const param = {
        id:id,
        status:e.target.checked
      }

      //根据id更改事项状态
      // 调用mutations中的changeStatus,传递param参数
      this.$store.commit('changeStatus',param)
    }
  }

然后打开store.js编写addItem

export default new Vuex.Store({
  ......
  mutations: {
    ........
    changeStatus(state,param){
      //根据id改变对应事项的状态
      const index = state.list.findIndex( x => x.id === param.id )
      if(index != -1) state.list[index].done = param.status
    }
  }
  ......
})

E.剩余项统计

打开store.js,添加getters完成剩余项统计

getters:{
  // 统计未完成的任务的条数
  unDoneLength(state){
    // 通过filter对list数组进行过滤,
    // 条件是每一项中如果done属性为false就过滤出来
    // 然后形成一个新数组
    const temp = state.list.filter( x => x.done === false )
    console.log(temp)
    // .length得到新数组的长度,即未完成的条数,返回出去
    return temp.length
  }
}

打开App.vue,使用getters展示剩余项

//使用映射好的计算属性展示剩余项
<!-- 未完成的任务个数 -->
<span>{{unDoneLength}}条剩余</span>

//导入getters
import { mapState,mapGetters } from 'vuex'
//映射
computed:{
  ...mapState(['list','inputValue']),
  // 将store中的getters的方法映射为计算属性
  ...mapGetters(['unDoneLength'])
}

F.清除完成事项

首先,打开App.vue文件,给“清除已完成”按钮绑定点击事件,编写处理函数

<!-- 把已经完成的任务清空 -->
<a @click="clean">清除已完成</a>

//编写事件处理函数
methods:{
  ......
  clean(){
    //清除已经完成的事项
    this.$store.commit('cleanDone')
  }
}

然后打开store.js编写addItem

export default new Vuex.Store({
  ......
  mutations: {
    ........
    // 清除已完成的任务
    cleanDone(state){
      // 先过滤出未完成的任务,然后重新赋值给list数组
      // 就相当于清除了已完成的任务
      state.list = state.list.filter( x => x.done === false )
    }
  }
  ......
})

G.点击选项卡切换事项

打开App.vue,给“全部”,“未完成”,“已完成”三个选项卡绑定点击事件,编写处理函数

并将列表数据来源更改为一个getters。因为需要切换数据,所以不能直接操作state中的数据,需要使用getters将数据进行包装,然后按需显示用户希望看到的数据,并且它不会修改源数据

<a-list bordered :dataSource="infoList" class="dt_list">
  ......
  <!-- 操作按钮 -->
  <a-button-group>
    <a-button :type="viewKey ==='all'?'primary':'default'" @click="changeList('all')">全部</a-button>
    <a-button :type="viewKey ==='undone'?'primary':'default'" @click="changeList('undone')">未完成</a-button>
    <a-button :type="viewKey ==='done'?'primary':'default'" @click="changeList('done')">已完成</a-button>
  </a-button-group>
  ......
</a-list>
//编写事件处理函数以及映射计算属性
methods:{
  ......
  changeList( key ){
    //点击“全部”,“已完成”,“未完成”时触发
    this.$store.commit('changeViewKey',key)
  }
},
computed:{
  // 将store中的全局的state数据映射为当前组件的一个计算属性
  ...mapState(['list','inputValue','viewKey']),
  ...mapGetters(['unDoneLength','infoList'])
}

打开store.js,添加getters,mutations,state

export default new Vuex.Store({
  state: {
    ......
    //保存默认的选项卡值
    viewKey:'all'
  },
  mutations: {
    ......
    changeViewKey(state,key){
      //当用户点击“全部”,“已完成”,“未完成”选项卡时触发
      state.viewKey = key
    }
  },
  ......
  getters:{
    .......
    infoList(state){
      if(state.viewKey === 'all'){
        return state.list
      }
      if(state.viewKey === 'undone'){
        return state.list.filter( x => x.done === false )
      }
      if(state.viewKey === 'done'){
        return state.list.filter( x => x.done === true )
      }
    }
  }
})
posted @ 2020-12-30 22:11  倚栏侧看花满楼  阅读(253)  评论(0)    收藏  举报