如何在<a>&#39;s href?

时间:2018-05-31 14:59:34

标签: javascript vue.js href

I need to create a dynamic link which makes use of a bound variable. The "dynamism" of the link is done though a modification of the href field with a bound variable ip:

new Vue({
  el: "#app",
  data: {
    ip: "10.1.1.1"
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17-beta.0/vue.js"></script>
<div id="app">
  <a href="http://example.com/{{ip}}">{{ip}}</a>
</div>

This does not work because {{ip}} is not interpolated and I get a warning

Interpolation inside attributes has been removed. Use v-bind or the colon shorthand instead. For example, instead of <div id="{{ val }}">, use <div :id="val">.

Switching href= into :href= breaks the template:

new Vue({
  el: "#app",
  data: {
    ip: "10.1.1.1"
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17-beta.0/vue.js"></script>
<div id="app">
  <a :href="http://example.com/ip">{{ip}}</a>
</div>

How can I use bound values in href?

EDIT: I cannot use a computed value (which would have been the first idea) because I am in a Buefy table and uses the data current to the row i am in (see https://codepen.io/WoJWoJ/pen/vrOgOX?editors=1010中使用绑定变量作为示例,props.row元素属性是我的ip

2 个答案:

答案 0 :(得分:0)

你可以将它与计算属性一起使用:

new Vue({
  el: "#app",
  data: {
    ip: "10.1.1.1"
  },
  computed: {
    ipUrl: function() {
      return `http://example.com/${this.ip}`;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17-beta.0/vue.js"></script>
<div id="app">
  <a :href="ipUrl">{{ip}}</a>
</div>

答案 1 :(得分:0)

你需要在:href内写一个JS表达式,比如

<a :href="'http://example.com/' + ip">IP</a>

注意双引号内的单引号(devoting string)(包含属性值/定义)。