当前位置: 首页 > Web前端 > vue.js

vue全家桶(4.2)

时间:2023-03-31 14:49:47 vue.js

.goods{背景颜色:绿色;宽度:250px;填充:16px;color:white;}.goodsspan{color:red}5.2.使用vuex重构上面的代码。什么是Vuex?官方定义:Vuex是专门为Vue.js应用开发的状态管理模型。它使用集中存储来管理应用所有组件的状态,并使用相应的规则来保证状态以可预测的方式变化Vuex使用步骤:1安装Vuexnpminstallvuex--save2在src目录下,新建storefile文件夹,在store文件夹下新建index.js文件3在index.js文件中输入如下代码importVuefrom'vue'importVuexfrom'vuex'//让vuex作为vue的插件使用Vue.use(Vuex)//创建一个容器letstore=newVuex.Store()//导出这个store实例,方便注入到vue中。exportdefaultstore4将store实例注入vue,引入storeimportVuefrom'vue'importinmain.jsAppfrom'./App'importrouterfrom'./router'import'@/assets/style/index.css'从'@/store/index'导入商店Vue.config.productionTip=false/*eslint-disableno-new*/newVue({el:'#app',router,store,render:h=>h(App)})接下来,我们需要使用vuex来管理状态,第一步,设置一个共享数据,在store/index.js中操作//创建一个容器letstore=newVuex.Store({state:{goods_num:0}})2.将这个状态映射到视图上,在components/VuexShoppingCar.vue中操作.goods{背景颜色:绿色;宽度:250px;填充:16px;color:white;}.goodsspan{color:red}3.提交一个mutation,这个mutation类似于js中的一个事件,有一个事件类型和一个事件处理函数,我们改变全局的goods_num在事件处理函数,下面是VuexGoodsItem组件中的代码4.在store中添加一个mutation,在store/index.js中运行importVuefrom'vue'importVuexfrom'vuex'//让vuex作为一个vue插件使用Vue.use(Vuex)//创建一个容器letstore=newVuex.Store({state:{goods_num:0},mutations:{changeCar(state,num){console.log(state)state.goods_num+=num}}})//导出这个store实例,方便在vue中注入exportdefaultstore注意:在第3步中,this.$store.commit('changeCar',this.num)这句话提交的changeCar,真正执行的逻辑在第4步,mutation设置的changeCar