4***@qq.com
4***@qq.com
  • 发布:2021-06-07 16:49
  • 更新:2021-06-07 18:00
  • 阅读:409

vuex的使用

分类:uni-app

vuex使用

store/index.js如下

import Vue from 'vue'  
import Vuex from 'vuex'  

Vue.use(Vuex)  

const store = new Vuex.Store({  
  state: {  
    name:''  
  },  
  getters: {  
    name:(state)=>{  
        return state.name  
    }  
  },  
  mutations: {  
    changeName (state,aname) {  
      state.name=aname  
    }  
  },  
  actions: {  
  }  
})  

export default store

我们项目中有一个utils.js,在该文件中使用获取store的值为空

import store from '@/store/index.js  
function test(){  
   console.log(store.getters.name);//打印出来为空  
}

在首页nvue页面里

<template>  
    <view>  
        你好,{{name}}  
        <view class="container" @click="test()">  
            点击修改名字  
        </view>  
    </view>  
</template>  

<script>  
    import { mapGetters,mapMutations } from 'vuex'  

    export default {  
        data() {  
            return {}  
        },  
        computed:{  
            ...mapGetters([  
              'name'  
            ])  
        },  
        methods: {  
            //方法  
            ...mapMutations([  
              'changeName'  
            ]),  
            test(e){  
                this.changeName('test');  
                                console.log(this.$store.getters.name);//打印出来为:test  
            }  
        }  
    }  
</script>  

<style>  
</style>

问题:为什么外部js文件中的store.getters.name和vue页面的this.$store值不一样? 在外部JS文件中要怎么获取到正确的值?

2021-06-07 16:49 负责人:无 分享
已邀请:
深海智行

深海智行 - 专注前端培训

参考一下 hello uni-app

  • 4***@qq.com (作者)

    hello uni-app好像没有在单独的js文件中使用

    2021-06-07 16:55

DCloud_UNI_LXH

DCloud_UNI_LXH

utils.js中,是设置后再调用的吗?

  • 4***@qq.com (作者)

    在页面中import这个utils.js使用:import {test} from '@/common/utils/util';

    utils.js: module.exports={test:test}

    2021-06-07 17:47

  • 4***@qq.com (作者)

    o我的首页是nvue页面

    2021-06-07 17:51

4***@qq.com

4***@qq.com (作者)

在nvue页面中,main.js通过Vue.prototype.$**定义的全局变量也无法访问?

该问题目前已经被锁定, 无法添加新回复