+
95
-

vue父子组件之间如何进行传值通讯?

vue

vue父子组件之间如何进行传值通讯?

网友回复

+
15
-

一、父组件调用子组件方法

vue中如果父组件想调用子组件的方法,可以在子组件中加上ref,然后通过this.$refs.ref.method调用,例如:

父组件:
<template>
  <div @click="fatherMethod">
    <child ref="child"></child>
  </div>
</template>
<script>
  import child from '~/components/dam/child.vue';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {this.$refs.child.childMethods();
      }
    }
  };
</script>

子组件:

在父组件中, this.$refs.child 返回的是一个vu...

点击查看剩余70%

+
15
-

如果是cdn的方式使用vue直接在浏览器中执行,父子组件之间的通讯代码如下:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum=1.0,minimum=1.0,user-scalable=0" />
    <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/vue@2.6.1-dev.js"></script>

    <style>
        .comment-box{
        padding: 5px 10px;
        border: 1px solid grey;
        margin:5px;
        }
        .reply{
        color: red;
        font-weight: bold;
       
        }
    </style>
</head>

<body>

    <div id="app">

        <div id="comment">
            <Reply :commentdata="comments" v-on:replyit="replyit"></Reply>
        </div>
        <form><input :placeholder="touser" id="replycontent" />
            <input type="hidden" id="toid" :value="toid" /><input type="button" value="回复" /></form>
    </div>
    <script type="text/javascript">
   
        Vue.component('Reply',{
            template: '<div><div class="comment-box" v-for="item in commentdata"><span>{{item.nickname}}说</span> <span>{{item.content}}</span> <span @click="replyit(item.id,item.nickname)" class="reply">回复</span><Reply v-bind="$attrs" v-on="$listeners" v-if="item.replyComments" :commentdata="item.replyComments" ></Reply></div></div>',
            props: ['commentdata'],
            data: function () {
                return {
           
                };
            },
            mounted: function () {
           
            },
           ...

点击查看剩余70%

我知道答案,我要回答