1. 程式人生 > 其它 >vue子元件傳父元件

vue子元件傳父元件

1、子元件created中this.$emit兩個引數(要傳給誰,要傳的資訊) 2、@定義一個方法,用於接收son傳過來的資訊 3、得到son傳過來的資訊,固定引數data 4、父元素data中定義資料用來接收使用來自son的資訊 5、將得到的data值(這裡的data是自定義方法中的data)傳給data中定義好的資料中使用 6、使用son傳來的資訊
<!DOCTYPE html>
<html>
<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></title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
    <div id='app'>
        <father></father>
    </div>
    <template id="father">
        <div>
            {{fathermsg}}
            
<!-- 6、使用son傳來的資訊 --> {{usesonmsg}} <!-- 2、@定義一個方法,用於接收son傳過來的資訊 --> <!-- 定義getsonmsg方法接收son傳來的資訊 --> <son @send-msg-to-father='getsonmsg'></son> </div> </template> <template id="son"> <div> {{sonmsg}}
</div> </template> <script> Vue.component('father',{ template:'#father', data(){ return{ fathermsg:'父元素資訊', usesonmsg:''//4、定義資料用來接收使用來自son的資訊 } }, methods:{
// 3、得到son傳過來的資訊,固定引數data getsonmsg(data){ console.log(data);// 列印結果 子元素資訊 this.usesonmsg = data//5、將得到的data傳給usesonmsg使用 } } }) Vue.component('son',{ template:'#son', data(){ return{ sonmsg:'子元素資訊' } }, created(){ // 1、this.$emit兩個引數(要傳給誰,要傳的資訊) // 把this.sonmsg傳給fromson this.$emit('send-msg-to-father',this.sonmsg) } }) const vm = new Vue({ el: '#app', data: { }, methods: { }, }) </script> </body> </html>