• 父子组件通信(vuex的方式)


    转: 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
    

      

  • 相关阅读:
    维度漫谈
    维度漫谈
    世界名曲
    世界名曲
    音乐的要素
    音乐的要素
    POJ 1300 欧拉通路&欧拉回路
    C库函数笔记
    malloc()参数为0的情况
    层层递进Struts1(三)之Struts组成
  • 原文地址:https://www.cnblogs.com/laneyfu/p/9523911.html
Copyright © 2020-2023  润新知