转: https://blog.csdn.net/lzh5997/article/details/80407518html
父子组件也能够经过vuex的进行来进行中转,其实vuex就相似与一个仓库,父组件把东西放到仓库,而后子组件,从仓库里面去出东西,由于子组件里面是经过计算属性来获取的值(具备实时性),一旦父组件从新改变了数据,子组件就会从新从vuex里面读取数据vue
father.vuevuex
<template> <div> <h4>父组件</h4> <child></child> <button @click="transmitData">经过vuex给子组件传值</button> </div> </template> <script> import Child from './child.vue' export default { components: { Child }, data() { return { testData: '我是父组件传递给子组件的值' } }, methods: { transmitData() { // 经过commit提交数据改变vuex里面的数据 this.$store.commit('fatherData', this.testData) } } } </script> <style scoped> </style>
child.vuethis
<template> <div> <p v-if="_fatherData === null">暂无数据</p> <p v-else>{{_fatherData}}</p> </div> </template> <script> export default { computed:{ _fatherData(){ // 读取store里面的值 return this.$store.state.fatherDatas } } } </script> <style scoped> </style>
store.jsspa
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ // 初始化的数据 state: { fatherDatas: null }, // 改变state里面的值得方法 mutations: { fatherData(state, data) { state.fatherDatas = data } } }) // 输出模块 export default store