使用vuex交流两个组件时出现问题

时间:2019-09-17 05:08:17

标签: vue.js vue-component vuex vuex-modules

我一直在尝试交流两个组件,一个是作为父节点的登录名,另一个是嵌套节点,因为调查和vuex可以帮助我集中信息并使之在所有组件中可见,但是我可以无法进行交流,我已经完成了一个新项目来测试示例,并且当我想将这些示例传递到我的应用程序时它们是否有效  组件A

   <temaplte>
      <button @click="addTodo()">addTodo</button>
      <ul>
        <li v-for="(todo, index) in todos" :key="index">
          {{ todo.text }}
          <button @click="removeTodo(todo)">x</button>
        </li>
      </ul>
   </template>


import store from "../../../store/index";
        data:{

        return{
            other: "all"

           }
        }

          computed: {
         todos() {
              return this.$store.getters[this.other];
            }
        }


          methods: {
           addTodo() {
              store.commit("addTodo", ["hi", "bye"]);
            }
          }

enter image description here

组件B

<template>
<button @click="getData">Show Console Data</button>
</template>
import store from "../../../store/index";

data:{
return
{
info: []
}
}

 methods: {
    getData() {
      this.info =this.$store.getters.all
      return console.log(this.info)
    }
}

输出

enter image description here

商店/ index.js

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

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        todos: []
    },
    mutations: {
        addTodo({ todos }, text) {
            todos.push({
                text,
                completed: false
            })
        },
        removeTodo: ({ todos }, todo) => {
            todos.splice(todos.indexOf(todo), 1)
        },
        markTodo({ todos }, todo) {
            todos[todos.indexOf(todo)].completed = !todo.completed
        },
        markAllTodo({ todos }, completed) {
            todos.forEach(todo => (todo.completed = completed))
        },
        clearCompleted({ todos }) {
            todos.map(
                todo => (todo.completed ? todos.splice(todos.indexOf(todo), 1) : null)
            )
        }
    },
    getters: {
        all: state => state.todos,
        completed: state => state.todos.filter(todo => todo.completed),
        pending: state => state.todos.filter(todo => !todo.completed)
    }
})

0 个答案:

没有答案