Vue.js中父组件获取子组件属性以及子组件传递属性给父组件

如何传递?

首先先定义好父组件和子组件,然后在父组件中引入子组件,并使用标签。
然后在父组件中的子组件标签中使用引用ref=引用名来确定想要引用的子组件,之后在父组件中就可以用this.$refs.引用名的形式获取子组件实例,this.$refs.引用名.属性名的形式获取子组件的属性。
而子组件想要主动传值给父组件,需要在子组件中使用this.$emit(事件名称,想要传递的值)来声明想要传递的值和事件名称,然后在父组件的子组件标签上使用@事件名称=函数名称来监听事件,并在methods中用对应函数名称的函数来接收,其参数data就是传递来的值。

父组件代码

<template>
  <div>
    <div style=background-color:#55FF22>
      <span>这是父组件</span><br>
      <span>获取到的子组件的值为:{{pmsg}}</span><br>
      <button @click=getcmsg>获取子组件中的值</button>
    </div>
    <childdiv ref=childref @parentEvent=showMsgFromChild></childdiv><br>
    <span>子组件主动传来的值为:{{msgfromchild}}</span>
  </div>
</template>
<script>
import child from ./Child;
export default {
  data(){
    return{
      pmsg:,
      msgfromchild:
    }
  },
  components: {
    childdiv: child
  },
  methods:{
    getcmsg:function(){
      this.pmsg  = this.$refs.childref.cmsg;
    },
    showMsgFromChild:function(data){
      this.msgfromchild = data
    }
  }
};
</script>

子组件代码

<template>
  <div>
    <span>这是子组件</span><br>
    <span>子组件中cflag的值为:{{cmsg}}</span>
    <button @click=sendtop>主动传递属性给父组件</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cmsg: ' from child 父组件请求',
      toparent: 'from child主动传递'
    };
  },
  methods:{
    sendtop:function(){
        this.$emit(parentEvent,this.toparent);
    }
  }
};
</script>

最终效果

父子组件传值

评论

  1. 114514
    5 年前
    2019-4-06 20:21:51

    你是岛民吗?

    • hafuhafu
      博主
      114514
      5 年前
      2019-4-06 21:13:57

      只有岛上才有岛民

      • ATM
        hafuhafu
        5 年前
        2019-4-06 21:51:09

        你是bog吗

        • hafuhafu
          博主
          ATM
          5 年前
          2019-4-06 23:12:21

          我是鸟卫乒

          • A哥不要啊
            hafuhafu
            5 年前
            2019-4-06 23:40:50

            菜鸡前端交流群(目前就2个岛民) 来商业互吹啊

          • hafuhafu
            博主
            A哥不要啊
            5 年前
            2019-4-10 21:37:57

            自闭儿童好慌啊

  2. 5 年前
    2019-4-07 12:52:52

    昨天想着注册这个域名来着,一查发现已经被你得手了。真是可恶!

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇