【问题标题】:Vue js -- accessing props through methods failedVue js——通过方法访问props失败
【发布时间】:2019-12-28 13:57:58
【问题描述】:

我将一个组件(组件 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>

【问题讨论】:

  • @Phil 需要帮助^^
  • 考虑使用ref属性,然后通过this.$refs引用
  • @IVO GELOV,非常感谢,但我试过了,没有运气。
  • 你能告诉我们你是怎么尝试的吗?我在您的代码中没有看到任何引用。
  • 在一些不相关的上下文中,像 vue 这样的框架的目的是删除直接的 dom 修改,例如 getElement。在 vue 中使用事件绑定不是比获取元素更好的方法吗?

标签: javascript vue.js vue-props


【解决方案1】:

如果我理解正确,您希望iconClassName 可以点击吗?

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

为此,您可以使用 Vue 的 v-on attribute。 @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>

【讨论】:

    猜你喜欢
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 2014-06-19
    • 1970-01-01
    • 2013-12-13
    相关资源
    最近更新 更多