Vue学习之--------深入理解Vuex之多组件共享数据(2022/9/4)

在上篇文章的基础上:Vue学习之--------深入理解Vuex之getters、mapState、mapGetters

1、在state中新增用户数组

在这里插入图片描述

2、新增Person.vue组件

提示:这里使用nanoid来生成新用户的id。nanoid的安装:npm i nanoid
如果提示权限不够,使用管理员命令窗口

只需要引入另外一个组件中操作的state的数据

  computed: {
    personList() {
      return this.$store.state.personList;
    },
    //另外一个组件操作的数据
    Count(){
        return this.$store.state.sum
    }
  },
<template>
  <div>
    <h1>人员信息展示</h1>
    <h3 style="color:pink">Count组件的和为:{{Count}}</h3>
    <input type="text" placeholder="请输入姓名" v-model="name" />
    <button @click="add">添加</button>
    <ul>
      <li v-for = "p in personList" :key = "p.id">{{p.name}}</li>
    </ul>
  </div>
</template>

<script>
import {nanoid} from 'nanoid'
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
export default {
  name: "Person",
  data() {
    return {
      name: "",
      n: 1,
    };
  },
  methods: {
      add(){
          const personObj = {id:nanoid(),name:this.name}
          this.$store.commit('ADD_PERSON',personObj)
          this.name = ''
      }
  },
  computed: {
    personList() {
      return this.$store.state.personList;
    },
    Count(){
        return this.$store.state.sum
    }
  },
};
</script>

<style lang="css">
</style>


3、在Count组件中使用Person组件操作的数据

首先引入
在这里插入图片描述
然后使用
在这里插入图片描述

4、测试效果

在这里插入图片描述

posted on 2022-09-05 08:28  热爱技术的小郑  阅读(47)  评论(0编辑  收藏  举报