简体   繁体   English

Vue v-model 绑定问题

[英]Vue v-model bind issue

Hi I have been on this issue for several days now.嗨,我已经讨论这个问题好几天了。 I am trying to bind data to input text using v-model of Vue.我正在尝试使用 Vue 的 v-model 将数据绑定到输入文本。 My Vue is installed in my project, and the cdn link added in header.我的Vue安装在我的项目中,并且在header中添加了cdn链接。 The textbox simply shows the data for a split second on reload and then disappears.文本框仅在重新加载时显示一瞬间的数据,然后消失。 Is it maybe an installation problem?可能是安装问题? I installed npm vue directly in my Laravel project on my console.我在控制台的 Laravel 项目中直接安装了 npm vue。

My HTML:我的 HTML:

<div id='postEdit'>

  <input type="text" name="title" id="title" class="form-control" v-model="post.body">

</div>

My Vue:我的 Vue:

var edit = new Vue({
  el: '#postEdit',
  data: {
    post: {
      body: 'this is body'
    }
  },

});

My output when I run edit.post in console:我在控制台中运行 edit.post 时的输出:

Object { body: Getter & Setter, … }

Your data property is wrong, it needs to be a function returning an object.您的 data 属性是错误的,它需要是一个返回对象的函数。 Change like this:像这样改变:

data () {
  return {
    post: {
      body: 'this is body'
    }
  }
}

Vue.js documentation says that in data option you MUST use Plain objects : Vue.js 文档说在data选项中你必须使用普通对象

Vue will recursively convert its properties into getter/setters to make it “reactive”. Vue 会递归地将其属性转换为 getter/setter 以使其“反应”。 The object must be plain : native objects such as browser API objects and prototype properties are ignored.对象必须是普通的:浏览器 API 对象和原型属性等原生对象将被忽略。 A rule of thumb is that data should just be data - it is not recommended to observe objects with their own stateful behavior.一个经验法则是数据应该只是数据——不建议观察具有自己状态行为的对象。

For your example I'd go with a computed property returning the body property of your post .对于您的示例,我将使用计算属性返回您的postbody属性。

I mean something like this JSFiddle .我的意思是这样的 JSFiddle

Just make your data a function and check again.只需将您的数据设为函数并再次检查即可。 proof证明

<div id='postEdit'>
  <input type="text" name="title" id="title" class="form-control" v-model="post.body">
</div>

var edit = new Vue({
el: '#postEdit',
data: function() { 
  return {
      post: {
      body: 'this is bodygfdgfd'
      }
   }
 }
});

oh, and this console thing... try edit.post.body哦,还有这个控制台的东西……试试 edit.post.body

You see {getter, setter} because Vue "compiles" data object using Object.defineProperty method to observe changes in data.您会看到 {getter, setter} 因为 Vue 使用 Object.defineProperty 方法“编译”数据对象来观察数据的变化。 Under the hood getters works just fine, trust me ;)引擎盖下的吸气剂工作得很好,相信我;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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