首页 > 解决方案 > 我需要在短时间内学习 vuex,因为我不知道如何将我的 vue js 迁移到 vuex?

问题描述

这是我的 github 页面,您可以在帮助分支中看到我所做的:https ://github.com/maltin1234/blog

我需要更改组件中的代码,但我不知道如何。

创建组件.vue

    <template>
  <div>
    <h1>Create A Post</h1>
    <form @submit.prevent="addPost">
      <div class="row">
        <div class="col-md-6">
          <div class="form-group">
            <label>Post Title:</label>
            <input type="text" class="form-control" v-model="post.title" />
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col-md-6">
          <div class="form-group">
            <label>Post Body:</label>
            <textarea
              class="form-control"
              v-model="post.body"
              rows="5"
            ></textarea>
          </div>
        </div>
      </div>
      <br />
      <div class="form-group">
        <button class="btn btn-primary">Create</button>
      </div>
    </form>
  </div>
</template>
export default {

<script>
export default {
  name: "CreateComponent",
  data() {
    return {
      title: "",
    };
  },
  methods: {
    ...mapActions(["addPost"]),
    onSubmit(e) {
      e.preventDefault();
      this.addPost(this.title);
    },
  },
};
</script>

我有一个节点 js 后端,我希望我的 vuex 获取这些端点。node js 后端由一个 mongodb 连接和一个带有文章的模型组成。这是我对 vuex 的尝试。

post.js(vue.js 项目)

import axios from "axios";

const state = {
  posts: [],
};

const getters = {
  allPosts: (state) => state.Posts,
};

const actions = {
  //an action: makes a request, gets a response and calls a mutation
  async fetchPosts({ commit }) {
    // commit - to call the mutation
    const response = await axios.get("http://localhost:4000/posts");
    commit("setPosts", response.data);
  },
  async addPosts({ commit }, title) {
    const response = await axios.post("", { title, completed: false });
    commit("newPost", response.data);
  },
  async deletePosts({ commit }, id) {
    await axios.delete(`http://localhost:4000/posts/delete/${id}`);
    commit("removePosts", id);
  },
  async filterPosts({ commit }, e) {
    //Get selected number
    // const limit = parseInt(e.target.options[e.target.options.selectedIndex].innerText);
    const limit = e.target.value;
    const response = await axios.get(`http://localhost:4000/posts`);
    commit("setPosts", response.data);
  },
  async updatePosts({ commit }, updatePosts) {
    const response = await axios.put(
      `http://localhost:4000/posts/update/${this.$route.params.id}`,
      updatePosts
    );
    console.log(response.data);
    commit("updatePosts", response.data);
  },
};

const mutations = {
  setPosts: (state, Posts) => (state.posts = posts),
  newPosts: (state, posts) => state.posts.unshift(posts),
  removePosts: (state, id) =>
    (state.posts = state.posts.filter((posts) => posts.id !== id)),
  updatePosts: (state, updTodo) => {
    const index = state.Posts.findIndex((posts) => posts.id === updPosts.id);
    if (index !== -1) {
      state.posts.splice(index, 1, updPosts);
    }
  },
};

export default {
  state,
  getters,
  actions,
  mutations,
};

store.js

import Vuex from "vuex";
import Vue from "vue";
import todos from "./modules/todos";

//load Vuex

Vue.use(Vuex)

//create store
export default new Vuex.Store({
    modules: {
        posts
    }
})

节点项目(https://github.com/maltin1234/blognode

标签: javascriptnode.jsvue.jsvuex

解决方案


首先,要使用 Vuex,您必须创建商店并将其添加到项目中,然后要使用任何操作/状态/getters/setter,您必须通过 vuex 方法将它们导入组件,例如:

import { mapActions, mapState } from 'vuex'
export default {
    computed: {
        ...mapState('yourModule', ['stateValueOne', 'stateValueTwo'])
    },
    methods: {
        ...mapAction('yourModule', ['actionOne', 'actionTwo'])
    }
}

然后你可以通过this标识符获取它们只需查看 Vuex API 参考,这很简单


推荐阅读