【问题标题】:Unable to bind text to href attribute in VueJS template无法将文本绑定到 VueJS 模板中的 href 属性
【发布时间】:2020-08-10 02:11:12
【问题描述】:

我正在使用 VueJS 构建模板。

根据我的“帖子”数据,我已经能够使用以下方法将文本绑定到 spanap 等 html 元素中小胡子语法。但是,当我尝试将文本绑定到 a 元素中的元素属性(例如 href)时,它不起作用。

我看过不同的教程,但没有一个具体说明如何在同一代码中将文本绑定到元素它们的属性 - 大多数都显示一个或另一个但不在同一个模板中一起显示。


我的 HTML 如下所示:

<div id="app">
  <div class="container-fluid">
    <ul class="list-group">
      <post v-for="post in posts" :post="post"></post>
    </ul>
  </div>
</div>

<template id="post-template">
  <li class="list-group-item">
    <a :href="{{posts.url}}">{{ post.title }}</a>
    <p>{{post.text}}</p>
  </li>
</template>

我的 JS 看起来像这样:

Vue.component('post', {
  template: "#post-template",
  props: ['post']
});

var vm = new Vue({
  el: "#app",
  data: {
    posts: [
         {
             title: "First post!",
             text: "First text",
             url: "www.firsturl.com"
         },
         {
             title: "Second post!",
             text: "Second text",
             url: "www.secondurl.com"
         },
         {
             title: "Third post!",
             text: "Third text",
             url: "www.thirdurl.com"
         }
    ]}
});

See my code in JSFiddle

【问题讨论】:

  • 属性不需要花括号::href="post.url"

标签: javascript html vue.js templates vue-component


【解决方案1】:

在属性中,你必须直接指出 props 或 JS 表达式,不要留胡子:

<a :href="url">{{ post.title }}</a>

【讨论】:

    【解决方案2】:

    你不需要在文本绑定上使用双括号:

    <a :href="post.url">{{ post.title }}</a>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-15
      • 2019-08-12
      • 1970-01-01
      相关资源
      最近更新 更多