• vuex的一个demo,数据拿到界面上


    1.拿到store的一个值,并实现自增

     1 <template>
     2     <div>
     3         <button @click="add">add</button>
     4         {{getuser}}
     5     </div>
     6 </template>
     7 <script>
     8 import {mapState,mapActions} from 'vuex'
     9 export default {
    10     data () {
    11         return {
    12             // 在data中拿到user值,赋值给getuser
    13             getuser: this.$store.state.user
    14         }
    15     },
    16     methods: {
    17         //设置一个方法add控制data里的getuser自增
    18         add (){
    19             this.getuser++
    20         }
    21     },
    22     computed: {
    23     }
    24 }
    25 </script>

    2.用辅助函数拿到store里的值,并用store里的方法操作

     1 <template>
     2     <div>
     3         <button @click="contorlSetUserFn(2)">add</button>
     4         {{user}}
     5     </div>
     6 </template>
     7 <script>
     8 import {mapState,mapActions} from 'vuex'
     9 export default {
    10     data () {
    11         return {
    12 
    13         }
    14     },
    15     methods: {
    16         //使用辅助函数拿到方法
    17         ...mapActions(["contorlSetUser"]),
    18         contorlSetUserFn(a){
    19             this.contorlSetUser(a)
    20         }
    21     },
    22     computed: {
    23         //使用辅助函数拿到了user值
    24         ...mapState(["user"])
    25     }
    26 }
    27 </script>

    3.我的store,配置数据持久化

     1 Vue.use(Vuex);
     2 
     3 const Store = new Vuex.Store({
     4     state:{
     5         user:1
     6     },
     7     mutations:{
     8         setUser(state,newuser = 1){
     9             state.user += newuser
    10         }
    11     },
    12     actions:{
    13         contorlSetUser({commit},newuser){
    14             //user对应mutations里面的一个方法名
    15             commit("setUser",newuser)
    16         }
    17     },
    18     // 默认保存到localStorage
    19     // plugins:[createPersistedState()],
    20     plugins:[createPersistedState({
    21         //  修改成sessionStorage    
    22         storage:window.sessionStorage
    23     })],
    24     
    25     modules:{}
    26 })
    27 
    28 export default Store
  • 相关阅读:
    java环境变量配置(Windows & Linux)
    转行自学编程的前提条件和能力
    IntelliJ IDEA 视频教程
    小孩都懂得用“头衔”来包装自己了,那么你呢?
    自创“乒乓球自嗨玩法”
    什么是npm以及npm基本命令
    hexo本地搭建以及在github远程部署
    如何下载Java-配置环境全教程
    图的存储结构以及遍历
    二叉树的存储结构以及遍历
  • 原文地址:https://www.cnblogs.com/GGbondLearn/p/12639450.html
Copyright © 2020-2023  润新知