簡體   English   中英

Vue js——通過方法訪問props失敗

[英]Vue js -- accessing props through methods failed

我將一個組件(組件 1)中的一個 prop 傳遞給另一個組件(組件 2),相關的方法(在組件 2 中具有傳遞/給定的 props 值)起作用。 然后我嘗試將方法放在組件 1 中並將方法中的給定值更改為內部動態證明,它停止工作。

肯定是訪問方式的問題:

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

請幫忙!

<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>

如果我理解正確,您希望iconClassName是可點擊的?

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

為此,您可以使用 Vue 的v-on 屬性 @click="alertWechat"應該可以解決問題。 此外,這會縮短您的代碼並使其更具可讀性。

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM