Uniapp中vuex使用出现的问题
正在做一个微信小程序,很多地方还都不是很懂,就比如数据共享报错,看了很多博客都没解决,求助各位热心的前端程序员,希望能得到帮助,一直报错真的好难受
一、初始化vuex
新建store.js,挂载到main.js
1、在根目录下创建store文件夹,用来存放vuex相关模块
2、在store中新建store.js文件
3、在store.js中初始化Store的实例对象
//1.导入Vue和Vuex
import Vue from 'vue'
import Vuex from 'vuex'
//2.将 Vuex 安装为 Vue 的插件
Vue.use(Vuex)
// 3.创建 Store 的实例对象
const store = new Vuex.Store({
// 挂载 store 模块
modules: { }
})
// 4.向外共享 Store 的实例对象
export default store
4、在main.js中导入store实例对象并挂载到vue的实例上
// 1、 导入 store 的实例对象
import store from '@/store/store.js'
const app = new Vue({
...App,
// 2、 将 store 挂载到 Vue 实例上
store
})
app.$mount()
二、创建store模块
新建cart.js,挂载到store.js
1、在store文件夹中新建cart.js文件
2、在cart.js中初始化vuex模块
export default {
namespaced: true,
state: () => ({
// 购物车的数组,用来存储购物车中每个商品的信息对象
// 每个商品的信息对象,都包含如下6个属性:
// { goods_id,goods_name,goods_price,goods_count,goods_small_logo,goods_state }
cart: []
}),
mutations: {},
getter: {}
}
3、在 store.js 中,导入并挂载 购物车cart的 vuex 模块
import Vue from 'vue'
import Vuex from 'vuex'
// 1、导入购物车cart的 vuex 模块
import moduleCart from '@/store/cart.js'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
// 2、挂载购物车的 vuex 模块,模块内成员的访问路径被调整为 m_cart 例如:
// 购物车模块中 cart 数组的访问路径是 m_cart/cart
'm_cart': moduleCart
}
})
export default store
使用store中的数据
import { mapState } from 'vuex'
export default {
computed: {
// 调用 mapState 方法, 把m_cart 模块中的 cart 数组映射到当前页面中,作为计算属性来使用
// ...mapSate('模块的名称',['要映射的模块里的数据名称'])
...mapState('m_cart', ['cart'])
},
然后在页面中测试是否能正常使用
<view class="yf">快递:免运费{{cart.length}}</view>
然后就是报错,一直不知道问题在哪,下图为报错信息
还有就是在main.js中导入出现的问题,当把导入代码写在#ifndef中可以正常编译
但是,当把导入语法放在#ifnde外面编译器就报错,
诶,一直不知道怎么解决真的挺难受的,主要是项目做不下去,希望我的问题能得到解决,感谢阅读