vue 基础入门笔记 13:父组件向子组件传值、父组件向子组件传递方法

vue 基础入门笔记 13

  1. 父组件向子组件传值: prop 是父组件用来传递数据的一个自定义属性。子组件需要显式地用 props 选项 声明 “prop”:
  2. 父组件向子组件传递方法: @方法名 = 父组件的方法 子组件通过 $this.emit( '方法名' , [可传递参数] )
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    </head>
    <body>
    <div id="app">
        //父组件向子组件传递方法  
        <son @func='show' :msg="'hello world'"></son>
    </div>
    <template id="son">
        <div>
            <button @click = 'showLog' type="button" class="btn btn-danger">button</button>
            <label>
                {{msg}}
            </label>
        </div>
    </template>
    <script>
        Vue.component('son', {
            //对子组件进行传值
            //数据只可读 无法重新赋值
            props: ['msg'],
            template: '#son',
            methods:{
                showLog(){
                    // 通过this.$emit('函数名')来调用父组件传递的方法,剩下的参数可传递数据
                    this.$emit('func','B')
                    console.log("aaaa")
                }
            }
        })
        var vm = new Vue({
            el: '#app',
            data: {},
            methods: {
                show(data) {
                    console.log("执行了事件A------"+data)
                }
            }
        });
        Vue.config.devtools = true
    </script>
    </body>
    </html>
本作品采用《CC 协议》,转载必须注明作者和本文链接
日照香炉生紫烟
September
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!