Vue 动态添加子组件属性以及自定义事件

2021-06-22  本文已影响0人  王二麻子88

通过 v-bindv-on 实现

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>测试Vue动态绑定数据</title>
    </head>
    <body>
        <div id="app">
            <div id="parent">{{msg}}</div>
            <child v-bind="parmas" v-on="event"></child>
        </div>
        <template id="childComponent">
            <div id="child">
                <p>{{child}}</p>
        <div class="title">{{title}}</div>
        <div class="sub-title">{{subTitle}}</div>
        <button @click="clickEvent"> 点击 </button>
        <button @click="closeEvent"> 关闭 </button>
      </div>
        </template>
        <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.0/vue.js"></script>
        <script>
            const childComponet = {
                template: '#childComponent',
                props: ["title", "subTitle"],
        data() {
                    return {
                        child: 'child',
                    }
                },
        methods: {
          clickEvent() {
            this.$emit("cusClick", "click")
          },
          closeEvent() {
            this.$emit("close", "close")
          }
        },
        mounted() {
          console.log(this.title);
          console.log(this.subTitle);
        }
            }
            Vue.component('child', childComponet)
            const App = new Vue({
                el: '#app',
                data() {
                    return {
                        msg: 'hello',
            parmas: {
              title: "标题",
              subTitle: "副标题"
            },
            event: {
              cusClick: function() {
                console.log("触发点击事件")
              },
              close: function() {
                console.log("触发关闭事件")
              }
            }
          }
                },
                methods: {},
            })
        </script>
    </body>
</html>

上一篇 下一篇

猜你喜欢

热点阅读