美文网首页
Vue 动态添加子组件属性以及自定义事件

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

作者: 王二麻子88 | 来源:发表于2021-06-22 14:01 被阅读0次

通过 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>

相关文章

网友评论

      本文标题:Vue 动态添加子组件属性以及自定义事件

      本文链接:https://www.haomeiwen.com/subject/lkzpyltx.html