【问题标题】:Combine v-bind and v-for in vue.js (and webpack) v-bind ignored在 vue.js(和 webpack)中结合 v-bind 和 v-for 忽略 v-bind
【发布时间】:2018-05-15 23:08:03
【问题描述】:

我想将内联样式绑定到包含 v-for 的 div。但它似乎总是忽略 v-bind。这是模板和数据。

<template>
    <div id="app">
      <div v-bind:style="styleObject" v-for="collection in collections" :key="collection.id">       
       <a v-bind:href="collection.pageurl">  
         <h1>{{ collection.title }}</h1>
         <h2>{{ collection.author }}</h2>             
      </a>   
    </div>
    <router-view/>
    </div>
    </template>

...这是同一个 .vue 文件中的脚本代码:

export default {
  name: "app",
  styleObject: {
    background: "red",
    borderColor: "red"
  },
  //Pass data to the app.
  firebase: {
    collections: collectionsRef
  }
};

背景图片将来自表格,但我什至无法让这个简单的静态示例工作。除了 v-bind 被忽略之外,一切都按预期呈现。当我在 chrome 中检查时,style= 甚至不在 div 标签中。我从 vue.js 文档中复制了 v-bind 代码。我正在使用带有 webpack 的 vue-cli。

没有错误信息,代码编译正常。 v-bind 被忽略了。

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    styleObject 必须是组件数据或计算属性的一部分。我假设 collectionsRef 对您来说工作正常,尽管根据发布的代码它似乎是未定义的。

    export default {
      name: "app",
      data(){
        return {
          styleObject: {
            background: "red",
            borderColor: "red"
          }, 
        }
      },
      //Pass data to the app.
      firebase: {
        collections: collectionsRef
      }
    };
    

    【讨论】:

    • 谢谢,这行得通。我看了一遍,从未见过这种语法。 (collectionsRef 在别处被定义为来自 firebase 项目的数据)。
    • 您使用的是组件,因此 data 必须是返回对象的函数。这在documentation on components 的前几段中进行了讨论。如果您还没有阅读它,那么文档非常好。
    【解决方案2】:

    让你的代码像这样。

    data : return{
       styleObject: {
        background: "red",
        borderColor: "red"
      }
    }
    

    【讨论】:

    • 您能详细说明一下吗?
    • 把你的 JS 发给我
    猜你喜欢
    • 2017-07-04
    • 2019-02-08
    • 2018-11-23
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 2018-12-20
    相关资源
    最近更新 更多