简体   繁体   中英

Unable to bind text to href attribute in VueJS template

I am using VueJS to build a template.

From my 'posts' data, I have been able to bind text into html elements such as span , a , and p using the Mustache syntax. But when I try to bind text into an element attribute such as href within the a element, it does not work.

I have looked at different tutorials but none show specifically how I can bind text to elements and their attributes within the same code - most show one or the other but not together in the same template.


My HTML looks like this:

<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>

My JS looks like this:

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

In attributes you have to indicate props or JS-expressions directly without mustaches:

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

You dont need to use double bracket on text bind:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM