Vue2.0 组件参数传递获取进阶

1、父组件访问子组件: 使用 $children 或 $refs

$children 示例

下面这段代码定义了3个组件:父组件 parent-component,两个子组件 child-component1 和 child-component2。

在父组件中,通过 this.$children 可以访问子组件。
this.$children 是一个数组,它包含所有子组件的实例。

<div id="app">
    <parent-component></parent-component>
</div>

<template id="parent-component">
    <child-component1></child-component1>
    <child-component2></child-component2>
    <input type="button" value="显示子组件的数据" v-on:click="showChildComponentData" >
</template>

<template id="child-component1">
    <h2>This is child component 1</h2>
</template>

<template id="child-component2">
    <h2>This is child component 2</h2>
</template>

<script>
    Vue.component('parent-component', {
        template: '#parent-component',
        components: {
            'child-component1': {
                template: '#child-component1',
                data: function() {
                    return {
                        msg: 'child component 111111'
                    }
                }
            },
            'child-component2': {
                template: '#child-component2',
                data: function() {
                    return {
                        msg: 'child component 222222'
                    }
                }
            }
        },
        methods: {
            showChildComponentData: function() {
                for (var i = 0; i < this.$children.length; i++) {
                    alert(this.$children[i].msg)
                }
            }
        }
    })

    new Vue({
        el: '#app'
    })
</script>
$refs 示例

组件个数较多时,我们难以记住各个组件的顺序和位置,通过序号访问子组件不是很方便。
在子组件上使用 ref 指令,可以给子组件指定一个索引 ID。

<template id="parent-component">
    <child-component1 ref="cc1"></child-component1>
    <child-component2 ref="cc2"></child-component2>
    <button v-on:click="showChildComponentData">显示子组件的数据</button>
</template>

// 在父组件中,则通过$refs.索引ID访问子组件的实例:
showChildComponentData: function() {
    alert(this.$refs.cc1.msg);
    alert(this.$refs.cc2.msg);
}

2、子组件访问父组件: 使用 $parent

下面这段代码定义了两个组件:child-component和它的父组件parent-component。
在子组件中,通过this.$parent可以访问到父组件的实例。

<div id="app">
    <parent-component></parent-component>
</div>

<template id="parent-component">
    <child-component></child-component>
</template>

<template id="child-component">
    <h2>This is a child component</h2>
    <button v-on:click="showParentComponentData">显示父组件的数据</button>
</template>

<script src="js/vue.js"></script>
<script>
    Vue.component('parent-component', {
        template: '#parent-component',
        components: {
            'child-component': {
                template: '#child-component',
                methods: {
                    showParentComponentData: function() {
                        alert(this.$parent.msg)
                    }
                }
            }
        },
        data: function() {
            return {
                msg: 'parent component message'
            }
        }
    })
    new Vue({
        el: '#app'
    })
</script>

注意:尽管可以访问父链上任意的实例,不过子组件应当避免直接依赖父组件的数据,尽量显式地使用 props 传递数据。另外,在子组件中修改父组件的状态是非常糟糕的做法,因为:

  1. 这让父组件与子组件紧密地耦合;

  2. 只看父组件,很难理解父组件的状态。因为它可能被任意子组件修改!理想情况下,只有组件自己能修改它的状态。

3、如何使用 props 来显式地传递参数。

// 父组件
<template>
  <div id="app">
    <Display></Display>
    <br>
    <Increment></Increment>
    <br>
    <p>--------------------------------------------------</p>
    <input type="text" v-model="msg" name="">
    <Child v-bind:parentmsg="msg" v-on:child-say="valueUp"></Child>
    <br>
    <p>{{childMes}}</p>
    <!-- <span style="font-family: tahoma, arial, helvetica, sans-serif; font-size: 16px">
      <p @valueUp ="recieve">{{childMes}}</p>
    </span> -->
  </div>
</template>

<script>
import Display from './display'
import Increment from './increment'
import Child from './child'

import { mapState, mapGetters, mapActions } from 'vuex'

export default {
  components: {
    Display: Display,
    Increment: Increment,
    Child: Child
  },
  data () {
    return {
      msg: 'wangzhe',
      childMes: ''
    }
  },
  computed: {
    ...mapState({
    }),
    ...mapGetters([
      'getCount'
    ])
  },
  methods: {
    ...mapActions([
      'updateMessage'
    ]),
    valueUp (mes) {
      this.childMes = mes
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>
// 子组件
<template>
  <div>
    <h4>{{parentmsg}}</h4>
    <input type="text" name="" v-model="inputValue">
    <br>
    <br>
    <p>---------------------------------------------------------</p>
    <input type="button" name="" value="点击" @click="enter">
  </div>
</template>

<script>
  import { mapState, mapGetters, mapActions } from 'vuex'
  
  export default {
    props: ['parentmsg'],
    data () {
      return {
        inputValue: ''
      }
    },
    computed: {
      ...mapState({
        age: 'count'
      }),
      ...mapGetters([
        'getCount'
      ])
    },
    methods: {
      ...mapActions([
        'updateMessage'
      ]),
      enter () {
        this.$emit('child-say', this.inputValue)
      }
    }
  }
</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,406评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,732评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,711评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,380评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,432评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,301评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,145评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,008评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,443评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,649评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,795评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,501评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,119评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,731评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,865评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,899评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,724评论 2 354

推荐阅读更多精彩内容