Vuex warehouse modular data sharing, father to son, son to father, $emit

 

Table of contents

1. Vue basic writing method

 2. Basic usage of vuex

 3. Shorthand for vuex

4. vuex modularization

5. From father to son

6. Child and Father

7.$emit


1. Vue basic writing method

<template>
  <div class="hello">
    <h1>计算</h1>
    <h3>和为:{
   
   { num }}</h3>
    <select name="1" id="" v-model.number="n">
      <!-- 加上冒号可以转为解析隐私转换为数字类型 或 事件修饰符number -->
      <option :value="1">1</option>
      <option :value="2">2</option>
      <option :value="3">3</option>
    </select>
    <button @click="jian">-</button>
    <button @click="jia">+</button>
    <button @click="odd">和为奇数才加</button>
    <button @click="wait">一秒之后加</button>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {},
  data() {
    return {
      // 使用了v-model 下拉框的默认值不生效,要自己设置不能为0
      n: 1,
      num: 0,
    };
  },
  methods: {
    jia() {
      this.num += this.n;
    },
    jian() {
      this.num -= this.n;
    },
    odd() {
      if (this.num % 2 != 0) {
        this.num += this.n;
      }
    },
    wait() {
      setTimeout(() => {
        this.num += this.n;
      }, 1000);
    },
  },
};
</script>

 2. Basic usage of vuex

1. Read data this.$store.state.property name

2. Operation data this.$store.dispacth("actions method name', parameter)

          Or this.$store.commit("mutations method name", parameter)

1. To get data from other servers, you need to send a request through the method in actions to process the data and then call the method of mutations

2. If you don’t need to take data from other servers, you can directly commit and call the method in mutations

<template>
  <div class="hello">
    <h1>计算</h1>
    <!-- 使用 $store.state.num 获取state的数据 这里不用this.是因为{
   
   {}}会全局去找这个属性 -->
    <h3>和为:{
   
   { $store.state.num }}</h3>
    <!-- $store.getters.方法名  把计算属性的方法当变量使用 -->
    <h3>和的十倍为:{
   
   { $store.getters.sum }}</h3>
    <select name="1" id="" v-model.number="n">
      <!-- 加上冒号可以转为解析隐私转换为数字类型 或 事件修饰符number -->
      <option :value="1">1</option>
      <option :value="2">2</option>
      <option :value="3">3</option>
    </select>
    <button @click="jian">-</button>
    <button @click="jia">+</button>
    <button @click="jiaodd">和odd为奇数才加</button>
    <button @click="jiawait">一秒之后加</button>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {},
  data() {
    return {
      // 使用了v-model 下拉框的默认值不生效,要自己设置不能为0
      n: 1,
      num: 0,
    };
  },
  methods: {
    jia() {
      // this.num += this.n;
      // dispatch 调用actions的方法和传递参数
      // this.$store.dispatch("jia", this.n);
      // commit直接联系mutations的计算属性
      this.$store.commit("JIA", this.n);
    },
    jian() {
      // this.num -= this.n;
      // 调用actions的方法
      // this.$store.dispatch("jian", this.n);
      // 调用mutations的方法
      this.$store.commit("JIAN", this.n);
    },
    jiaodd() {
      // if (this.num % 2 != 0) {
      //   this.num += this.n;
      // }
      // 使用 this.$store.state.num 获取state的数据
      // if (this.$store.state.num % 2 != 0) {
      //   this.$store.dispatch("jia", this.n);
      // }
      this.$store.dispatch("jiaodd", this.n);
    },
    jiawait() {
      // setTimeout(() => {
      //   // this.num += this.n;
      //   this.$store.dispatch("jia", this.n);
      // }, 1000);
      this.$store.dispatch("jiawait", this.n);
    },
  },
};
</script>

Write in the vuex folder

import Vue from "vue";
import Vuex from "vuex";
//使用vuex插件
Vue.use(Vuex);

export default new Vuex.Store({
  // 数据
  state: {
    num: 0,
  },
  // 计算属性
  getters: {
    sum(state) {
      // 必须使用return 把方法名当变量使用
      return state.num*10
    }
  },
  // 响应组件的动作 响应其他服务器
  actions: {
    // jia(context, val) {
    //   context.commit("JIA", val);
    // },
    // jian(context, val) {
    //   context.commit("JIAN", val);
    // },
    jiaodd(context, val) {
      if (context.state.num % 2 != 0) {
        context.commit("JIA", val);
      }
      // 其他的处理程序
      // context.dispatch("demo1",val)
    },
    // demo1(context, val) {
    //   console.log("处理程序1");
    //   context.dispatch("demo2", val);
    // },
    // demo2(context, val) {
    //    console.log("处理程序2");
    //   // context.dispatch("demo3", val);
    // },
    jiawait(context, val) {
      setTimeout(() => {
        context.commit("JIA", val);
      }, 1000);
    },
  },
  // 方法 开发者工具捕获这里的变化
  mutations: {
    JIA(state, val) {
      state.num += val;
    },
    JIAN(state, val) {
      state.num -= val;
    },
  },
});

If you want to process multi-step programs for the same event, you can separate continuous triggers (synchronous execution)

 

 3. Shorthand for vuex

Shorthand for properties and methods

1. It is recommended to use the array writing method. The method name of the current page is the same as the attribute name in the state, which can be omitted as a value

 2. Object writing method The method name of the current page is the same as the attribute name in the state and cannot be omitted as a value

Automatic import 

import { mapActions, mapGetters, mapMutations, mapState } from "vuex";

computed property 

computed: {
    // num() {
    //   return this.$store.state.num;
    // },
    // sum() {
    //   return this.$store.getters.sum;
    // },
    // name() {
    //   return this.$store.state.name;
    // },
    // age() {
    //   return this.$store.state.age;
    // },
    // gender() {
    //   return this.$store.state.gender;
    // },
    // 简写
    // 在state里面找该属性名 当前页面使用的方法名:"state的属性名"  相同的方法名和属性名不能简写为一个name
    // 对象写法
    // ...mapState({num:"num" ,name: "name", age: "age", gender: "gender" })
    // 数组写法
    ...mapState(["num", "name", "age", "gender"]),
    // 在getters里面找方法名
    // ...mapGetters({ sum: "sum" }),
    ...mapGetters( ["sum"] ),
  },
// 数据
  state: {
    num: 0,
    name: "小白",
    age: 18,
    gender:"女"
  },
  // 计算属性
  getters: {
    sum(state) {
      // 必须使用return 把方法名当变量使用
      return state.num*10
    }
  },
 <h2>{
   
   { name }}是个{
   
   { age }}岁的小{
   
   { gender }}孩</h2>

 Write method methods inside

Pay attention to setting (parameters) if you do not set parameters, the default parameter is event, and an error will be reported! ! !

    <button @click="jian(n)">-</button>
    <button @click="jia(n)">+</button>
    <button @click="jiaodd(n)">和odd为奇数才加</button>
    <button @click="jiawait(n)">一秒之后加</button>

 mutations

// 对象 当前页面方法名:mutations的方法名 默认参数event 在调用方法的时候要主动传参(n)
    ...mapMutations({ jia: "JIA", jian: "JIAN" }),
    // 数组 这边方法名和那边的方法名相同数组才可以这样简写
    // ...mapMutations(["JIA", "JIAN"]),

actions 

// 对象
    // ...mapActions({ jiaodd: "jiaodd", jiawait: "jiawait" }),
    // 数组
    ...mapActions(["jiaodd", "jiawait"]),

4. vuex modularization

Classify different data types to facilitate data management

Add another list component

<template>
  <div class="about">
    <h1>人员列表</h1>
    <h3 style="color:pink">计算求和为:{
   
   { num }}</h3>
    <input type="text" placeholder="请输入要添加的名字" v-model="val" />
    <button @click="add(val)">添加</button>
    <ul>
      <li v-for="(item, index) in preson" :key="index">{
   
   { item }}</li>
    </ul>
  </div>
</template>
<script>
import { mapState,mapMutations } from "vuex";

export default {
  data() {
    return {
      val: "",
    };
  },
  methods: {
    // add(val) {
    //   this.$store.commit("ADD", val);
    //   this.val = "";
    // },
    ...mapMutations({add:'ADD'}),
  },
  computed: {
    // num() {
    //   return this.$store.state.num
    // },
    // preson() {
    //   return this.$store.state.preson
    // },
    ...mapState(["num", "preson"]),
  },
};
</script>

The data on both sides are shared, and they are all taken in one place

 state: {
    num: 0,
    name: "小白",
    age: 18,
    gender: "女",
    preson:["小白","小黑"]
  },
...mapState(["num", "name", "age", "gender", "preson"]),

It is inconvenient to manage all the data mixed together, and it is necessary to distinguish types and modularize

Core: Use the namespace, otherwise when you use it, you need to. That category

 namespaced: true
import Vue from "vue";
import Vuex from "vuex";
import numder from "./numder.js"
import preson from "./preson.js";
//使用vuex插件
Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
 // 命名
    numder,
    preson,
  },
});

Create folders by category and import them into the same folder using namespace distinction 

 

Method ...mapGetters('named',["sum"]),

// 模块化命名区分
    ...mapState("numder", ["num", "name", "age", "gender", "preson"]),
    ...mapState("preson", ["preson"]),
    // 在getters里面找方法名
    // ...mapGetters({ sum: "sum" }),
    ...mapGetters('numder',["sum"]),
...mapMutations('numder',{ jia: "JIA", jian: "JIAN" }),
...mapActions('numder',["jiaodd", "jiawait"]),

How to write your own method Name /method

methods: {
    add(val) {
      this.$store.commit("preson/ADD", val);
      this.val = "";
    },

5. From father to son

1. Define a data a:10 in the parent component data

2. Define a custom attribute on the child component tag of the parent component to pass in the data of the parent component  : a1="a"

3. Receive the attribute props["a1"] in the props of the subcomponent

4. Using this attribute in a subcomponent is equivalent to using  { {a1}} for the attribute value in data

5. You can define the data type and initial value when receiving

props:{

        a1:{

             type:Number,

             default:100

           }

}

6. Child and Father

1. Define a method  fun(){ console.log("parent component method")} in the methods of the parent component

2. Define a custom event on the child component tag of the parent component, and bind the defined method to this event

<com @k="fun"/>

3. Create a required event @click="fun2" in the subcomponent

4. Use it in the method of the subcomponent

fun2(){

   this.$emit("k", parameter, parameter 2)

}

5. Receive parameters to process data in the fun(){} method of the parent component, and realize the method of triggering the parent component through the child component

Summarize:

1. When the data is used in multiple components, put it in the vuex warehouse and pay attention to the classification and storage.

2. The data is stored directly in the current component only when the data is used in the current component.

3. The child component needs the data of the parent component to use the parent to pass the child,

4. When the parent component needs the data of the child component, it uses the child to pass the parent.

5. Subcomponents and subcomponents need to share data in the vuex warehouse

7.$emit

Pass parameters to other components through custom events

1. Create a bus.js folder

//content:

import Vue from "vue"

export default new Vue()

 2. Use $emit custom event to pass value in the component to be passed

//import

import bus from "@/components/bus.js";

//Used by event trigger

<button @click="send">Pass value to c component</button>

methods: {

    send() {

      bus.$emit("sendarr", this.arr);

    },

  },

 3. Listen to custom events and receive parameters in components that need to receive data

created() {

    // Listen to sendarr custom events

    bus.$on("sendarr", (data) => {

      console.log(data);

      this.arr = data;

    });

  },

 

 4. Pass the value directly to the c component by triggering the event

 

 

 5. If you want to use data in that component, just listen to that custom event in that component

Guess you like

Origin blog.csdn.net/weixin_70563937/article/details/126671728