vue組件之間的三種傳值方式


一、父組件向子組件傳值

首先父組件發送的形式是用bind綁定值到子組件身上,然后子組件數props屬性接收

<body>
    <div id="app">
        <!-- 父組件,可以在引用子組件的時候,通過屬性綁定的形式,把需要傳遞給子組件的數據,以屬性綁定的形式,傳遞到子組件內部,供子組件使用 -->
        <com1 :parentmsg="msg"></com1>
    </div>
</body>

</html>
<script>
    var vm = new Vue({
        el: "#app",
        data: {
            msg: "這是父組件中的數據"
        },
        methods: {},
        components: {
            com1: {
                data() {
                    // return {
                    //     title: "123",
                    //     content: "qqq"
                    // }
                },
                template: '<h1 @click="change">這是子組件 --- {{parentmsg}}</h1>',
                props: ['parentmsg'],
                // directives: {},
                // filters: {},
                // components: {},
                // methods: {
                //     change() {
                //         this.parentmsg = "被修改了"
                //     }
                // }
            }
        }
    })
</script>

二、子組件向父組件傳值

 

<body>
    <div id="app">
        <com2 @func="show"></com2>
    </div>
</body>
<template id="tmpl">
    <h1>這是子組件</h1>
    <h4>點擊按鈕獲取從父組件傳過來的 func 方法</h4>
    <input type="button" value="點擊" @click="myclick">
</template>

</html>
<script>
    var com2 = {
        template: '#tmpl',
        methods: {
            myclick() {
                this.$emit('func', this.sonmsg)
            }
        }
    }
    var vm = new Vue({
        el: "#app",
        data: {
            datamsgFormSon: null

        },
        methods: {
            show(data) {
                this.datamsgFormSon = data
            }
        },
        components: {
            com2: com2
        }
    })
</script>

三、非父子之間傳值

<body>
    <div id="app">
      <zs></zs>
      <ls></ls>
    </div>
  </body>
</html>
<script>
  var bus = new Vue();
  Vue.component("zs", {
    template: '<div>這是張山<button @click="sb">傳值</button></div>',
    methods: {
      sb() {
        bus.$emit("tt", {
          name: "我是zs"
        });
      }
    }
  });
  Vue.component("ls", {
    template: "<div>我是ls</div>",
    created() {
      bus.$on("tt", function(data) {
        console.log(data);
      });
    }
  });
</script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM