zoukankan      html  css  js  c++  java
  • 关于vue3简单状态管理约定引发的思考

    官方文档的代码是这样的

    export const store = {
      debug: true,
    
      state: reactive({
        message: 'Hello!'
      }),
    
      setMessageAction(newValue) {
        if (this.debug) {
          console.log('setMessageAction triggered with', newValue)
        }
    
        this.state.message = newValue
      },
    
      clearMessageAction() {
        if (this.debug) {
          console.log('clearMessageAction triggered')
        }
    
        this.state.message = ''
      }
    }
    

    当我使用的时候

        console.log(this.$store.state.message);
        this.$store.setMessageAction('你好');
        console.log(this.$store.state.message);
    

    输出的消息是这样的

    Hello!
    setMessageAction triggered with 你好
    你好
    

    这看起来没什么问题 但是当我这么使用的时候

        console.log(this.$store.state.message);
        this.$store.state.message='你好';
        console.log(this.$store.state.message);
    

    输出的消息是这样

    Hello!
    你好
    

    没有警告 直接绕过了setMessageAction方法

    看官网的介绍是约定而不是约束,这样如果在它处修改状态值,直接绕过set方法,可能会造成未知的后果

    不知道是我理解错了还是官网的意思就是让我们自己进行约束,有知道的大佬还望告知一下,

    贴一下我自己写的约束代码 不知道是不是正确的路子

    import { reactive, readonly } from 'vue';
    const user_info: IUserInfo = reactive({
      user_name: '',
      system_code: '',
      cellphone: null,
      email: ''
    });
    export const store = {
      /**
       * @description: 获取用户信息
       * @param {*}
       * @return {*}
       */
      getUserInfoAction(): IUserInfo {
        return readonly(user_info);
      },
      /**
       * @description: 设置用户信息
       * @param {string} user_name 用户名
       * @param {string} system_code 系统编码
       * @param {number} cellphone 手机号
       * @param {string} email 邮箱
       * @return {*}
       */
      setUserInfoAction(user_name: string, system_code: string, cellphone: number, email: string): void {
        user_info.user_name = user_name;
        user_info.system_code = system_code;
        user_info.cellphone = cellphone;
        user_info.email = email;
      },
    
    }
    /**
     * @description: userinfo数据结构
     * @param {string} user_name 用户名
     * @param {string} system_code 系统编码
     * @param {number} cellphone 手机号
     * @param {string} email 邮箱
     * @return {*}
     */
    interface IUserInfo {
      user_name: string,
      system_code: string,
      cellphone: number,
      email: string
    }
    
    

    -------------------------------------------

    学而不思则罔,思而不学则殆

    你好,我是【咬轮猫】

    -------------------------------------------

  • 相关阅读:
    Octave中的函数记录
    利用jira-python对jira项目
    通过python中xlrd读取excel表格(xlwt写入excel),xlsxwriter写入excel表格并绘制图形
    使用python的requests模块采集请求中的数据
    react+webpack+webstorm开发环境搭建
    Django中url使用总结
    通过Django中的forms类对前台的forms表单数据进行校验
    4.软件测试用例设计
    3.软件开发与测试模型
    16 IO流
  • 原文地址:https://www.cnblogs.com/Hero-/p/15098170.html
Copyright © 2011-2022 走看看