Javascript vue.js 给 <a> 标签中的 href 赋值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34842284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:56:15  来源:igfitidea点击:

vue.js Giving a value to a href in a <a> tag

javascripthtmllaravelvue.js

提问by commandantp

Sounds dumb but I can't find a way to pass a variable data defined in the href:

听起来很愚蠢,但我找不到传递href中定义的变量数据的方法:

ComponentFile.vue I tried all of those:

ComponentFile.vue 我尝试了所有这些:

<a href=" url ">{{ url }}</a>
<a href=" {{ url }}">{{ url }}</a>
<a href=" {{ url }}">{{ url }}</a>
<a v-bind:href="url">{{ url }}</a>
<a @click=" url " v-bind:href="url"> {{ url }}</a>


...
export default {
        data() {
                   url: 'http://anywhere.com'
  }
}

What is the correct way?

什么是正确的方法?

Thanks!

谢谢!

回答by Jeff

You've defined data()as a function, but it isn't returning anything. It should return an object with the data like so:

您已定义data()为一个函数,但它没有返回任何内容。它应该返回一个包含数据的对象,如下所示:

export default {
    data() {
        return {
            url: 'http://anywhere.com'
        }
    }
}

Then either of these will work:

然后其中任何一个都可以工作:

<a href="{{url}}">{{ url }}</a>
<a v-bind:href="url">{{ url }}</a>

EDIT FOR VUE 2:

为 Vue 2 编辑:

Interpolating variables in attributes is no longer recommended. Change:

不再建议在属性中插入变量。改变:

<a href="{{url}}">{{ url }}</a>

To one of these:

其中之一:

<a :href="url">{{ url }}</a>
<a v-bind:href="url">{{ url }}</a>

回答by Rafael Ferreira

Try this:

尝试这个:

<div id="app">
   <a href="{{ url }}">{{ url }}</a>
</div>
<script src="http://cdnjs.cloudflare.com/ajax/libs/vue/1.0.10/vue.min.js"></script>
<script>
  new Vue({
    el: '#app', // Vue.js will just work inside the div with id of app
    data: {
      url: 'http://anywhere.com' 
    }
  });
</script>