转: https://blog.csdn.net/lzh5997/article/details/80407518
父子组件也可以通过vuex的进行来进行中转,其实vuex就类似与一个仓库,父组件把东西放到仓库,然后子组件,从仓库里面去出东西,因为子组件里面是通过计算属性来获取的值(具有实时性),一旦父组件重新改变了数据,子组件就会重新从vuex里面读取数据
father.vue
<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.vue
<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.js
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