zoukankan      html  css  js  c++  java
  • Vue里父子组间的通讯

    父组件代码

    <template>
      <div>
        <child @child-say="listenToBoy" :mes=count></child>
        <p>Do you like me?{{this.word}}</p>
      </div>
    </template>
    <script>
      import child from '@/components/child.vue'
      export default {
        name: "parent",
        data() {
          return {
            count: 0,
            word: ''
          };
        },
        components: {
          child
        },
        methods:{
            listenToBoy(text){
                if (!this.word){
                    this.word = text
                    console.log('111')
                }else{
                    this.word = ''
                    console.log('else')
                }
            }
        }
      }
    
    </script>
    <style lang="css" scoped>
    </style>
    

      
    子组件代码

    <template>
        <div>
            <p>{{message}}</p>
            <button @click="add">add</button>
            <button @click="onClickMe">Click</button>
        </div>
    </template>
    <script>
    export default {
        name: "child",
        data () {
            return {
                message: this.mes,
                text: 'I love you'
            };
        },
        props: ['mes'],
        methods: {
            add (){
                this.message ++
            },
            onClickMe(){
                this.$emit('child-say', this.text)
            }
        }
        }
    </script>
    <style lang="css" scoped>
    </style>
    

      

    1.实现了将count的值通过props将父组件的值给子组件,用法:在父组件中的子组件标签绑定某个属性将要传的值跟在其后(如:mes=count,给子组件识别用的)传递,子组件用props:['mes']接收,子组件调用用this.mes

    2.子组件向父组件传值this.$emit(),用法:父组件监听某个属性(如@child-say='listenToBoy()')的方法,父组件方法中的形参来接收子组件传过来的值(如listenToBoy(text)),

    子组件在某处触发this.$emit('child-say',this.text)

  • 相关阅读:
    log4j日志配置
    map和java对象的转换方法
    阿里巴巴的json使用时的一些转换方法
    HttpClient发送Post和Get请求
    IT网站导航
    python学习
    git解决冲突
    协程
    Python实现协程
    异步任务神器 和定时任务Celery
  • 原文地址:https://www.cnblogs.com/jack-liu6/p/8977009.html
Copyright © 2011-2022 走看看