在weex中使用vuex,会报Cannot read property 'dispatch' of undefined,同样的代码在web下是能正常运行的,请教各位哪里写错了
entrt.js
import Vue from 'vue';
import weex from 'weex-vue-render';
import Vuex from 'vuex';
weex.init(Vue);
if (WXEnvironment.platform !== 'Web') {
Vue.use(Vuex);
}
store/countModule.js
import Vue from 'vue';
import Vuex from 'vuex'
if (WXEnvironment.platform !== 'Web') {
Vue.use(Vuex);
}
const state = {
count: 0
}
const mutations = {
increment(state) {
state.count++
},
decrement(state) {
state.count--
}
}
const actions = {
increment: ({ commit }) => commit('increment'),
decrement: ({ commit }) => commit('decrement'),
}
export default {
state,
actions,
mutations
}
store/store.js
import Vue from 'vue';
import Vuex from 'vuex';
import countModule from './countModule';
if (WXEnvironment.platform !== 'Web') {
Vue.use(Vuex);
}
export default new Vuex.Store({
modules: {
countModule
}
})
index.vue
<template>
<div class="wrapper">
<image :src="logo" class="logo" />
<text class="greeting">The environment is ready!</text>
<HelloWorld/>
<Display/>
<Count/>
</div>
</template>
<script>
import store from './store/store';
import HelloWorld from './components/HelloWorld.vue';
import Count from './components/count.vue';
import Display from './components/display.vue';
export default {
name: 'App',
store,
components: {
HelloWorld,
Count,
Display
},
data () {
return {
logo: 'https://gw.alicdn.com/tfs/TB1yopEdgoQMeJjy1XaXXcSsFXa-640-302.png'
}
}
}
</script>
<style scoped>
.wrapper {
justify-content: center;
align-items: center;
}
.logo {
width: 424px;
height: 200px;
}
.greeting {
text-align: center;
margin-top: 70px;
font-size: 50px;
color: #41B883;
}
.message {
margin: 30px;
font-size: 32px;
color: #727272;
}
</style>
count.vue
<template>
<div>
<div class="btn" @click="increment()"><text class="btn-text">点击+1</text></div>
</div>
</template>
<style scoped>
.btn{
background-color: #2e3e4c;
height: 50px;
line-height: 50px;
width:300px;
margin:20px auto;
}
.btn-text{
color: #fff;
text-align: center;
}
</style>
<script>
import { mapGetters, mapActions } from 'vuex'
var modal = weex.requireModule('modal');
export default {
methods:{
increment(){
// console.log(this.$store)
this.$store.dispatch('increment');
}
},
}
</script>
我也碰到了相同问题。解决方案如下:
因为 Vue.js 框架代码已经集成在 WeexSDK (0.9.5 以上)中,所以你不需要再引入一遍 Vue 。另外因为 Vuex 在浏览器环境下会自动注册,只需要在非 Web 环境下注册 Vuex 插件即可,重复注册的话会抛出警告的。引入 Vuex 的代码如下:
注册成功之后,所有 Vuex 的特性都能在 Weex 里使用! 具体用法以官方文档为准。
参考:
https://segmentfault.com/a/11...