【问题标题】:How can I change the href attribute in the script section in vue.js?如何更改 vue.js 脚本部分中的 href 属性?
【发布时间】:2019-11-21 06:10:00
【问题描述】:

我想将 href 属性设置为 item.AppUrl,它来自数据库并在方法部分呈现。

          <template v-if="header.value == 'ApplicationName'">
        <a id="url" href="#" target="_blank">{{renderData(props.item, header)}}</a>
      </template>

methods: {
  renderData: (item, header) => {
    if (header.value == 'ApplicationName') {
      document.getElementsByTagName("a")[0].setAttribute("href", item.AppUrl);
    }
    let val = "";
    if (header.value.includes('.')) {
      +
    const vals = header.value.split('.')
      val = vals.reduce((acc, val) => acc[val], item)
    } else {
      val = item[header.value]
    }
    if (typeof val === "boolean") {
      val = val ? "Yes" : "No";
    }
    return val;
  }
}

【问题讨论】:

  • 将 href 绑定到方法。即:href="renderData(...)"
  • 渲染错误:“TypeError:无法读取未定义的属性‘setAttribute’”
  • 来自这一行 - document.getElementsByTagName("a")[0].setAttribute("href", item.AppUrl);。看起来你也在尝试手动设置它。
  • 我真的不知道该怎么办。

标签: javascript html vue.js datatable vuetify.js


【解决方案1】:

您可以将方法的结果绑定到属性。下面,函数getUrl() 的结果使用: 绑定到href 属性(这是v-bind:href 的简写。这样做时,无需尝试在函数内手动设置属性。

var app = new Vue({
  el: '#app',
  data: {
   
  },
  methods: {
    getUrl: function(){
      // return any value to demonstrate how this works
      return "https://meta.stackoveflow.com";
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <a :href="getUrl()">This links to META Stack Overflow</a>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    • 2020-10-27
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 2012-09-18
    相关资源
    最近更新 更多