【问题标题】:Can't get data binding to work properly with vue无法让数据绑定与 vue 一起正常工作
【发布时间】:2019-10-31 09:54:08
【问题描述】:

我正在尝试创建一个 vue 应用程序。测试版is here。我正在处理的问题是 main.js 中的 vue 构造函数需要设置 Quote 对象的属性但不是。

Quote vue 文件有这个。

import card from './components/Card.vue'
import quoteheader from './components/QuoteHeader.vue'

export default{
  data: function(){
    return {
      title: "",
      quotecards: []
    }
  },
    methods: {
        addCard : function(obj){
            this.quotecards.push(
        {
          id: this.quotecards.length + 1,
          title: obj.title
        }
      );
      //console.log(this.quotecards);
        },
    updateCriteria(tmp){
      ///console.log(tmp);
    }
    },
  components: {
    card, quoteheader
  }
}

启动它的 main.js 有这个。

new Vue({
  el: "#app",
  render: h => h(Quote, {
    props: {
      title: "test",
        quotecards: [
            { id: 0, title: "title 1"},
            { id: 1, title: "title 2"}
        ]
    }
  })
})

当应用程序启动时,我希望quotecards 数据应该是一个包含 2 个项目的数组,并且quote vue 文件的模板字段中的文本字段应该具有“test”的值。相反,quotecards 长度为 0,输入为空。

【问题讨论】:

  • 请更新您的问题以包含您认为相关的代码部分,而不是依赖外部链接。
  • 问题已更新。

标签: vuejs2 vue-component


【解决方案1】:

main.js 中,您将titlequotecards 作为道具传递给Quote 组件。但是,对于该组件,这些并未定义为 props。相反,您已经让他们定义了一个本地 data

在一个组件中,访问dataprops 是一样的。例如this.title 在您的 JavaScript 中或只是在模板中 title。然而,它们是非常不同的东西。 Props 是从父组件传入的,而 data 是内部状态,由组件本身管理。

通常,组件只应更改其拥有的数据。因此,将 quotecards 设为 prop 会导致其他问题,因为您在 Quote 内对其进行了变异。处理此问题的首选方法是发出事件以通知父级quotecards 需要更改。父母如何做到这一点将取决于具体情况。如果值在父级上存储为data,则它是该数据的所有者,并且可以自行对其进行变异。

【讨论】:

  • 因此,如果 Quote 应该是唯一更改其 quotecards 属性的,我应该如何从 main.js 文件将该数据提供给组件?
猜你喜欢
  • 2020-08-02
  • 1970-01-01
  • 2016-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-27
  • 2012-06-21
  • 2015-09-28
相关资源
最近更新 更多