hendy0817
hendy0817

Reputation: 1079

Pass href from parent component to child component dynamically vue.js

So I have a modal that opens and has a "link out" button, this modal opens when a user clinks a link that directs to another site / page. What I want to do is open the modal and pass the HREF of the parent link to the modal "link out" button. I'm sure I could just add the link into the modal explicitly but I was wondering if there is a way to bind the link from the parent to the modal link out button dynamically.

Parent:

                   <template>
                     <div>
                      <a
                      @click.prevent="showInterstitial()"
                      href="https://www.linkout.com"
                      rel="noopener"
                      target="_blank"
                      >link out</a
                          >
                  </div>
              <Interstitial ref="openInterstitial"></Interstitial>
             </template>

<script>
import Interstitial from "~/components/blocks/modals/Interstitial.vue";

export default {
  components: {
    Interstitial
  },
  methods: {
    showInterstitial() {
      this.$refs.openInterstitial.showDialog();
    }
  }
};
</script>
         

Child:

<template>
  <div ref="openInterstitial" class="container--interstitial">
    <el-dialog :visible.sync="interstitialDialogVisible">
      <div class="dialog-content">
        <p class="font--primary">
          Dialog Content
        </p>

        <div class="buttons">
          <a class="button button--primary" href="PASSLINKHEREFROMPARENT" target="_blank">Ok</a>
          <button class="button button--secondary" @click="closeDialog()">
            Close
          </button>
        </div>
      </div>
      <!-- /.dialog-content -->
    </el-dialog>
  </div>
  <!-- /.container--interstitial -->
</template>

<script> 
export default {
  name: "Interstitial",
  components: {
    "el-dialog": Dialog
  },
  data() {
    return {
      interstitialDialogVisible: false
    };
  },
  methods: {
    showDialog() {
      this.interstitialDialogVisible = true;
    },
    closeDialog() {
      this.interstitialDialogVisible = false;
    }
};
</script>

   

Upvotes: 0

Views: 463

Answers (1)

Florian Pallas
Florian Pallas

Reputation: 582

You could remove the parenthesis from your showInterstitial method in the click event, like this:

<a @click.prevent="showInterstitial" href="https://www.linkout.com" ... />

That way, you can access the event object on your handler as parameter and therefore read the href property of the link.

As you are already calling a method on your modal to show it, you could just pass the data with a parameter.

Parent:

showInterstitial(e) {
  const href = e.target.href; // https://www.linkout.com
  
  this.$refs.openInterstitial.showDialog(href);
}

Child:

showDialog(href) {
  if(href) {
    // do stuff
  }
  this.interstitialDialogVisible = true;
},

Upvotes: 2

Related Questions