zoukankan      html  css  js  c++  java
  • vue 子组件接收父组件的另一种方法

    子组件获取父组件传递的数据通常是通过props属性接收父组件的传递过来的数据,代码如下:
    <!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>
    </head>
    <body>
    <div id="app">
    <my-child :msg='msg'></my-child>
    </div>
    </body>
    </html>
    <script src="./node_modules//vue//dist//vue.min.js"></script>
    <script>
    let vm = new Vue({
    el: '#app',
    data: {
    msg: 'helloword'
    },
    components: {
    'myChild': {
    props: ['msg'],
    mounted() {
    console.log(this.$attrs)
    },
    components: {
    'myChildren': {
    props: ['msg'],
    template:
    `<span>{{msg}}</span>
    `
    }
    },
    template: `<div>{{msg}}
    <my-children :msg='msg'></children>
    </div>`
    }
    }
    })
    </script>
    也可以通过子组件的$attrs接收的父组件的数据,但是这时候传递的数据子组件中不能有props的属性,不然子组件的$attrs获得的是空对象,代码如下:
    <!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>
    </head>
    <body>
    <div id="app">
    <my-child :msg='msg'></my-child>
    </div>
    </body>
    </html>
    <script src="./node_modules//vue//dist//vue.min.js"></script>
    <script>
    let vm = new Vue({
    el: '#app',
    data: {
    msg: 'helloword'
    },
    components: {
    'myChild': {
    // props:['msg'],
    mounted() {
    console.log(this.$attrs)
    },
    components: {
    'myChildren': {
    //props:['msg'],
    template:

    `<span>{{this.$attrs.msg}}</span>
    `
    }
    },
    template: `<div>{{this.$attrs.msg}}
    <my-children :msg='$attrs.msg'></children>
    </div>`
    }
    }
    })
    </script>
  • 相关阅读:
    第四次作业
    第三周
    作业
    第一周学习计划
    小组作业进度(只做了大概还未加内容)
    第六次作业
    第五次作业
    第四次作业
    复习心得 JAVA异常处理
    预习心得
  • 原文地址:https://www.cnblogs.com/zhx119/p/11096643.html
Copyright © 2011-2022 走看看