vue+axios+vuex 入坑基础例子

 

步骤:

1、下载安装vuex,或者引入

2、创建实例store

3、传送存储数据

4、读取数据(vuex刷新无数据,使用WEB储存 localStorage 和 sessionStorage)

 

实例化!

1.先设置储存的数据

2.在mutations 写入方法

3.用 this.$store.commit('方法名', 提交过去的数据) //触发

4.在mutations 写入方法里面处理完

5.在VUE的计算方法输出数据

 1 // 实例化
 2 const store = new Vuex.Store({
 3     state: { //需要储存的数据
 4         counts: 1,
 5         phoneSizeId: ''
 6     },
 7     //getters
 8     getters: { //获取状态及里面的数据
 9         getTotal(state) { //拿状态集里面的数据
10             return state.counts
11         }
12     },
13     // commit
14     mutations: { //动作 只能同步操作数据 不能做接口
15         // this.$store.commit('increment', this.price) //触发
16         increment(state, price) { //state 来改变 cound
17             // 变更状态
18             state.counts += price
19         },
20 
21         oneSize(state, phoneSize) { //state 对外通讯
22             // 变更状态
23             state.phoneSizeId = phoneSize
24         },
25 
26         decrement() {
27             state.counts -= price
28         }
29     },
30     //dispatch
31     actions: { //能在这里进行异步的操作 跟后端API接口放这里
32         //  this.$store.dispatch('increase', this.price) //触发
33         increase(context, price) { //做个中介再去执行
34             context.commit('increment', price)
35         }
36     }
37 })

 

 告诉VUE挂载上去 注入!

1 new Vue({ //實例對象
2     el: '#app', //裝載到什麼位置,標籤 ID CLASS
3     router, //用来渲染 外部引入的App组件  router:h=>h(App) 内置方法
4     store, //全局使用
5     template: '<App/>', //裝載 什麼樣的東西 HTML代碼 片段 模板
6     components: { App }
7 })

 

给vuex注入数据

1         methods: {
2             loadId(data, shopNames) {
3                 this.$router.push({ name: 'shopGoodsList', params: { id: data }, query: data })
4                 this.$store.commit('increment', shopNames) //触发
5                 sessionStorage.shopName = shopNames;
6             }
7         }

 

输出数据

1     computed: {
2             setName() {
3                 if (this.$store.state.shopNames) {
4                     return this.$store.state.shopNames;//输出传过来的数据
5                 } else {
6                     return sessionStorage.shopName;//输出浏览器保存的
7                 }
8             }
9         },

 

刷新后数据会消失?就这么处理!sessionStorage保存!

基本就处理完毕!

 

转载于:https://www.cnblogs.com/hasubasora/p/7491001.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值