1.安装
npm install vuex --save
2.在自己的项目目录下新建一个store文件夹,并新建一个index.js,并使用Vuex。代码如下:
复制代码
1
2
3import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex);
3.在main.js中,引入新建的store文件夹下的index.js
再然后 , 在实例化 Vue对象时加入 store 对象
复制代码
1
2
3
4
5
6import store from './store/index.js'; new Vue({ el: '#app', router: router, store: store })
这就ok了。我们就可以写vuex,并使用它了。
简单案例:
store/index.js
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) // 状态 const state = { helpdata:'', } // 可以对状态进行改变 const getters = { getHelpdata(state){ // 获取 return state.helpdata } } // 同步设置状态 const mutations = { setHelpdata(state, name) { // 设置 state.helpdata = name } } //异步获取状态 const actions = { }; export default new Vuex.Store({ state, getters, mutations, actions })
help.vue页面
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50<template> <div class="wrapper"> <header-title :title="productName" ></header-title> <div class="content"> <div v-for="item in helplist" > <group :title="item.helpcentername" > <span v-for="itemson in item.listbottoms"> <cell :title="itemson.helpcentername" is-link @click.native="helpparticulars(itemson.helpcenterdetails)"></cell> </span> </group> </div> </div> </div> </template> <script> import {mapMutations} from 'vuex' export default { data() { return { productName: "帮助中心", helplist:[], }; }, methods: { ...mapMutations(['setHelpdata']), // 获取页面数据 loaddate:function() { var params = {}; axios.post(params).then(res => { if (res.data.flag == 1) { if (res.data.success == 1) { this.helplist=res.data.data.list; } } }).catch(error => { console.log(error); }); }, //跳转详情页 helpparticulars:function(val){ this.setHelpdata(val); this.$router.push({path:'helpselfpage'}) } }, mounted() { this.loaddate(); }, }; </script>
helpselfpage.vue
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32<template> <div class="wrapper"> <header-title :title="productName"></header-title> <div class="content"> <section class="box"> <header class="box-header with-border" v-html="html" > </header> </section> </div> </div> </template> <script> import {mapGetters} from 'vuex' export default { data() { return { productName: "帮助中心", html:'' }; }, methods: { ...mapGetters(['getHelpdata']), // 获取页面数据 loaddate() { this.html=this.getHelpdata(); } }, mounted() { this.loaddate(); } }; </script>
最后
以上就是无心蜻蜓最近收集整理的关于Vuex的基本使用——同步设置状态情况下的全部内容,更多相关Vuex内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复