简体   繁体   中英

Vue js -- accessing props through methods failed

I am passing a proop in a component (component 1) to another one (component 2), the method related (which is in component 2 with passed/given props value) worked. Then i tried to put the method inside the component 1 and change the given value in the method to a internal dynamic proof, it stopped working.

It's for sure the problem of the way of accessing:

wechat = document.getElementsByClassName(`this.iconsClassName`)[0].childNodes[2];

please help!

<template>
  <div :class="iconsClassName">
    <div :class="iconClassName" v-for="(icon, index) in icons" :key="index">
      <a :href="icon.mediaLink" target="_blank">
        <svg style="width:16px;height:16px" viewBox="0 0 24 24">
          <path fill="#ffffff" :d="icon.icon" />
        </svg>
      </a>
    </div>
  </div>
</template>

<script>
export default {
  name: "mediaIcons",
  props: {
    iconsClassName: String,
    iconClassName: String,
    event: String
  },
  methods: {
    wechat() {
      let wechat = document.getElementsByClassName(this.iconsClassName)[0]
        .childNodes[2];
      wechat.addEventListener("click", alertWechat);
      function alertWechat() {
        alert("add me in weChat: eudora_neves");
        wechat.childNodes[0].removeAttribute("href");
      }
    },
  mounted: function() {
     this.wechat();
    }
  };
</script>

If I understood right, you want the iconClassName to be clickable?

<div class="iconClassName">
<!-- content -->
</div>

For this you can use Vue's v-on attribute . @click="alertWechat" should do the trick. Also, this would shorten your code and make it a bit more readable.

<template>
    <div :class="iconsClassName">
        <div 
            :class="iconClassName" 
            v-for="(icon, index) in icons" 
            :key="index" 
            @click="alertWechat"
        >
            <!-- content --> 
        </div>
    </div>
</template>

<script>
export default {
    name: "mediaIcons",
    props: {
        iconsClassName: String,
        iconClassName: String,
        event: String
    },
    methods: {
        function alertWechat() {
            //content
        }
    }
};
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM