美文网首页
vue简单的store模式

vue简单的store模式

作者: 秀萝卜 | 来源:发表于2022-07-22 16:02 被阅读0次

    https://blog.csdn.net/weixin_53181458/article/details/119909660

    大型项目中一般使用vuex作为数据存储。但是小项目中存储几个共用数据大可不必使用

    示例
    创建一个person.js文件,来储存某人的信息:

    //简单的store模块管理共享状态
    const Person = {
        state: {
            age: 6
        },
        setAge(age){
            this.state.age = age;
        }
    }
    //导出共享模块
    export default Person
    
    

    在其他组件中使用共享状态:

    //共享状态的改变是通过改变store模式储存的源信息来改变的
    <template>
      <div @click="chageAge">
        person age: {{this.shareState}}
      </div>
    </template>
    
    <script>
    import person from '@/store/person.js'
    
    export default({
      data() {
        return {
          //person.state改变时,组件中的shareState也会改变
          shareState: person.state
        }
      },
      methods: {
        chageAge() {
          const random = Math.floor(Math.random() * 10)
          const age = random
          //通过改变person.state来改变shareState,实现状态共享
          setAge(age)
        }
      }
    })
    </script>
    
    

    相关文章

      网友评论

          本文标题:vue简单的store模式

          本文链接:https://www.haomeiwen.com/subject/bcgmirtx.html