美文网首页
Vue父子组件传值

Vue父子组件传值

作者: 极度嫌弃 | 来源:发表于2019-04-28 17:38 被阅读0次

    父传子

    父组件 Father.vue

     <template>
        <div>
         <big-img  :imgSrc="imgSrc"></big-img>
        </div>
     </template>
    
    <script>
    import Son from "./Son.vue";
    export default {
     data() {
       return {
         imgSrc: "图片地址"
       };
     },
     components: {
        'big-img': Son
     }
    };
    </script>
    <style scoped>
    </style>
    

    子组件 Son.vue

    <template>
       <div>
           <img :src="imgSrc">
       </div>
    </template>
    <script>
    export default {
     props: ['imgSrc'],//接收父组件传过来的图片地址
     data(){
        return{
           }
       }
    }
    </script>
    <style scoped>
    </style>
    

    子传父

    子组件 Son.vue

    <template>
       <div  @click="imgMessage">
           <img :src="imgSrc">
       </div>
    </template>
    <script>
    export default {
     props: ['imgSrc'],
     methods: {
       imgMessage() {
         this.$emit('toFatherMessage',"这张图片真好看")
       }
     }
    }
    </script>
    <style scoped>
    </style>
    

    父组件 Father.vue

     <template>
        <div>
         <big-img  @toFatherMessage="viewImg"   :imgSrc="imgSrc"></big-img>
         <p>{{imgText}}</p>
        </div>
     </template>
    
    <script>
    import Son from "./Son.vue";
    export default {
     data() {
       return {
         imgSrc: "图片地址",
         imgText:""
       };
     },
     components: {
        'big-img': Son
     },
    methods:{
       viewImg(data){
         this.imgText=data;
       }
     }
    };
    </script>
    <style scoped>
    </style>
    

    相关文章

      网友评论

          本文标题:Vue父子组件传值

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