设为首页 加入收藏

TOP

Vue组件实例间的直接访问(二)
2017-10-10 15:34:07 】 浏览:8238
Tags:Vue 组件 实例 直接 访问

<div id="example">
  <parent-component></parent-component>
</div>
<template id="parent-component">
  <div class="parent">
    <h3>我是父组件</h3>
    <button @click="getData">获取子组件数据</button>
    <br>
    <div v-html="msg"></div>
    <child-component1></child-component1> 
    <child-component2></child-component2>   
  </div>
</template>
<template id="child-component1">
  <div class="child">
    <h3>我是子组件1</h3>
    <input v-model="msg">
    <p>{{msg}}</p>
  </div>
</template>
<template id="child-component2">
  <div class="child">
    <h3>我是子组件2</h3>
    <input v-model="msg">
    <p>{{msg}}</p>
  </div>
</template>
<script>
// 注册
Vue.component('parent-component', {
  template: '#parent-component',
  data(){
    return{
      msg:'',
    }
  },
  methods:{
    getData(){
      let html = '';
      let children = this.$children;
      for(var i = 0; i < children.length;i++){
        html+= '<div>' + children[i].msg + '</div>';
      }
      this.msg = html;
    }
  },
  components:{
    'child-component1':{
      template:'#child-component1',
      data(){
        return{
          msg:'',
        }
      },
    },
    'child-component2':{
      template:'#child-component2',
      data(){
        return{
          msg:'',
        }
      },
    }, 
  }   
})
// 创建根实例
new Vue({
  el: '#example',
})
</script>

<iframe style="width: 100%; height: 400px;" src="http://owbhsauev.bkt.clouddn.com/vue/module/m21.html" frameborder="0" width="320" height="240">

 

$refs

  组件个数较多时,难以记住各个组件的顺序和位置,通过序号访问子组件不是很方便

  在子组件上使用ref属性,可以给子组件指定一个索引ID:

<child-component1 ref="c1"></child-component1>
<child-component2 ref="c2"></child-component2>

  在父组件中,则通过$refs.索引ID访问子组件的实例

this.$refs.c1
this.$refs.c2
<div id="example">
  <parent-component></parent-component>
</div>
<template id="parent-component">
  <div class="parent">
    <h3>我是父组件</h3>
    <div>
      <button @click="getData1">获取子组件c1的数据</button>
      <p>{{msg1}}</p>
    </div>
    <div>
      <button @click="getData2">获取子组件c2的数据</button>
      <p>{{msg2}}</p>
    </div>
    <child-component1 ref="c1"></child-component1> 
    <child-component2 ref="c2"></child-component2>   
  </div>
</template>
<template id="child-component1">
  <div class="child">
    <h3>我是子组件1</h3>
    <input v-model="msg">
    <p>{{msg}}</p>
  </div>
</template>
<template id="child-component2">
  <div class="child">
    <h3>我是子组件2</h3>
    <input v-model="msg">
    <p>{{msg}}</p>
  </div>
</template>
<script>
// 注册
Vue.component('parent-component'
首页 上一页 1 2 3 下一页 尾页 2/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇JS倒计时——天时分秒 下一篇单文件文件上传到服务器(HTML5+j..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目