vuex超简单使用案例 替换创建好的新demo可直接使用

创建新项目 安装 vuex 后 替换文件可使用 vuex

create vuex1 // 创建项目

cd vuex1 // 进入项目

npm i // 安装依赖项

npm i vuex // 安装 vuex

写入文件:

src\store\index.js

src\components\HelloWorld.vue

src\store\index.js


import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);

const state = { // state数据
  week: '周一'
}

const getters = { // 相当于计算属性
  getweek: function (state) {
    console.log(state.week);
    return state.week.replace('周', '星期')
  }
}

const mutations = { //mutations定义同步操作的方法
  mutWeek(state, str) {
    state.week = '今天是:' + str;
  }
}

const actions = {  // actions 定义异步操作的方法
  actWeek(context, str) {
    context.commit('mutWeek', str);
  }
}

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})

src\components\HelloWorld.vue

<template>
  <div class="hello">
    <div>home的子组件</div>
    <br />
    <button @click="btn1">按钮 mapMutations</button>
    <button @click="btn2">按钮 mapActions</button>
    <hr />
    <!-- 把store.state的值直接显示 -->
    <div>mapState:{{this.$store.state.week}}</div>
    <br />

    <!-- 把getters的值直接显示 -->
    <div>mapGetters: {{getweek}}</div>
    <hr />
  </div>
</template>

<script>
// 把 getters mutations acitons 引入
import { mapGetters, mapMutations, mapActions } from "vuex";
export default {
  computed: {
    ...mapGetters(["getweek"]) //  mapGetters是指store里面的getters 的 getweek 方法
  },
  props: {
    msg: String
  },
  data() {
    return {
      falg: true
    };
  },
  methods: {
    ...mapActions(["actWeek"]), // 这里mapActions 的 actWeek 是指store里面的actions里的actWeek 方法
    ...mapMutations(["mutWeek"]), // 这里mapMutations 的 mutWeek 是指store里面的mutations里的 mutWeek 方法
    btn1() {
      // 点击后 执行mutWeek方法,会把值传入 store.mutWeek方法 改变 state.week的值
      this.mutWeek("周三 Mut"); // 执行 store里面的 mutWeek 同步方法 传入值
    },
    btn2() {
      this.actWeek("周五 Act"); // 执行 store里面的 actWeek 异步方法 传入值
    }
  }
};
</script>

<style scoped lang="scss">
.hello {
  background-color: rgb(86, 168, 201);
}
button {
  margin: 0 10px;
}
</style>


src\main.js

import Vue from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store' //引入 创建的store仓库

Vue.config.productionTip = false

new Vue({
  router,
  store,  //将store挂载到vue
  render: h => h(App)
}).$mount('#app')

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章