Vuex的基本使用——同步设置状态情况下

1.安装

npm install vuex --save

2.在自己的项目目录下新建一个store文件夹,并新建一个index.js,并使用Vuex。代码如下:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

3.在main.js中,引入新建的store文件夹下的index.js

再然后 , 在实例化 Vue对象时加入 store 对象 

import store from './store/index.js';

new Vue({
    el: '#app',
    router: router,
    store: store
})

这就ok了。我们就可以写vuex,并使用它了。


简单案例:

store/index.js

import 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页面

<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

<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>


猜你喜欢

转载自blog.csdn.net/xiasohuai/article/details/80677257